﻿namespace TfsCloudDeploy.Workflow.Core.Activities
{
    using System;
    using System.Text;
    using System.Runtime.InteropServices.ComTypes;
    using System.Runtime.InteropServices;
    using Microsoft.Win32.SafeHandles;
    using System.ComponentModel;
    using System.Security.AccessControl;
    using System.IO;
    using System.Security;
    using System.Drawing;
    using System.Security.Cryptography;
    using Microsoft.TeamFoundation;
    using System.Diagnostics;

    /// <summary>
    /// Reflected from: Microsoft.TeamFoundation.NativeMethods.
    /// Assembly: Microsoft.TeamFoundation.Common, Version=10.0.0.0.
    /// </summary>
    internal static class NativeMethods
    {
        // Fields
        internal const int AUTHZ_RM_FLAG_NO_AUDIT = 1;
        internal const int BCRYPT_PAD_PKCS1 = 2;
        internal const string BCRYPT_RSA_ALGORITHM = "RSA";
        internal const int BFFM_ENABLEOK = 0x465;
        internal const int BFFM_INITIALIZED = 1;
        internal const int BFFM_SELCHANGED = 2;
        internal static readonly int BFFM_SETSELECTION;
        internal const int BFFM_SETSELECTIONA = 0x466;
        internal const int BFFM_SETSELECTIONW = 0x467;
        internal const int CBN_DROPDOWN = 7;
        internal const int CDM_FIRST = 0x464;
        internal const int CDM_GETFILEPATH = 0x465;
        internal const int CDM_GETFOLDERIDLIST = 0x467;
        internal const int CDM_GETFOLDERPATH = 0x466;
        internal const int CDM_HIDECONTROL = 0x469;
        internal const int CDM_SETCONTROLTEXT = 0x468;
        internal const int CDM_SETDEFEXT = 0x46a;
        internal const int CDN_FILEOK = -606;
        internal const int CDN_FIRST = -601;
        internal const int CDN_FOLDERCHANGE = -603;
        internal const int CDN_HELP = -605;
        internal const int CDN_INCLUDEITEM = -608;
        internal const int CDN_INITDONE = -601;
        internal const int CDN_LAST = -699;
        internal const int CDN_SELCHANGE = -602;
        internal const int CDN_SHAREVIOLATION = -604;
        internal const int CDN_TYPECHANGE = -607;
        public const int CFE_LINK = 0x20;
        public const int CFM_LINK = 0x20;
        internal const int CRED_PACK_PROTECTED_CREDENTIALS = 1;
        internal const int CRED_PERSIST_LOCAL_MACHINE = 2;
        internal const uint CRED_TYPE_GENERIC = 1;
        internal const int CREDUI_FLAGS_ALWAYS_SHOW_UI = 0x80;
        internal const int CREDUI_FLAGS_COMPLETE_USERNAME = 0x800;
        internal const int CREDUI_FLAGS_DO_NOT_PERSIST = 2;
        internal const int CREDUI_FLAGS_EXCLUDE_CERTIFICATES = 8;
        internal const int CREDUI_FLAGS_EXPECT_CONFIRMATION = 0x20000;
        internal const int CREDUI_FLAGS_GENERIC_CREDENTIALS = 0x40000;
        internal const int CREDUI_FLAGS_INCORRECT_PASSWORD = 1;
        internal const int CREDUI_FLAGS_KEEP_USERNAME = 0x100000;
        internal const int CREDUI_FLAGS_PASSWORD_ONLY_OK = 0x200;
        internal const int CREDUI_FLAGS_PERSIST = 0x1000;
        internal const int CREDUI_FLAGS_REQUEST_ADMINISTRATOR = 4;
        internal const int CREDUI_FLAGS_REQUIRE_CERTIFICATE = 0x10;
        internal const int CREDUI_FLAGS_REQUIRE_SMARTCARD = 0x100;
        internal const int CREDUI_FLAGS_SERVER_CREDENTIAL = 0x4000;
        internal const int CREDUI_FLAGS_SHOW_SAVE_CHECK_BOX = 0x40;
        internal const int CREDUI_FLAGS_USERNAME_TARGET_CREDENTIALS = 0x80000;
        internal const int CREDUI_FLAGS_VALIDATE_USERNAME = 0x400;
        internal const int CREDUI_MAX_CAPTION_LENGTH = 0x80;
        internal const int CREDUI_MAX_MESSAGE_LENGTH = 0x7fff;
        internal const int CREDUI_MAX_PASSWORD_LENGTH = 0x100;
        internal const int CREDUI_MAX_USERNAME_LENGTH = 0x201;
        internal const int CREDUIWIN_AUTHPACKAGE_ONLY = 0x10;
        internal static readonly int CRYPT_ACQUIRE_SILENT_FLAG = 0x40;
        internal const int CS_DROPSHADOW = 0x20000;
        internal const int CSIDL_DESKTOP = 0;
        internal const int DEFAULT_GUI_FONT = 0x11;
        public static int DELETE = 0x10000;
        internal const int DT_CALCRECT = 0x400;
        internal const int DT_END_ELLIPSIS = 0x8000;
        internal const int DT_MODIFYSTRING = 0x10000;
        internal const int DT_PATH_ELLIPSIS = 0x4000;
        internal const int DT_SINGLELINE = 0x20;
        internal const int DWL_MSGRESULT = 0;
        internal const int EC_LEFTMARGIN = 1;
        internal const int EC_RIGHTMARGIN = 2;
        internal const int EM_CANUNDO = 0xc6;
        internal const int EM_CHARFROMPOS = 0xd7;
        internal const int EM_EMPTYUNDOBUFFER = 0xcd;
        internal const int EM_GETLINE = 0xc4;
        internal const int EM_GETLINECOUNT = 0xba;
        internal const int EM_GETMODIFY = 0xb8;
        internal const int EM_GETPASSWORDCHAR = 210;
        internal const int EM_GETSEL = 0xb0;
        internal const int EM_LIMITTEXT = 0xc5;
        internal const int EM_LINEFROMCHAR = 0xc9;
        internal const int EM_LINEINDEX = 0xbb;
        internal const int EM_POSFROMCHAR = 0xd6;
        internal const int EM_REPLACESEL = 0xc2;
        internal const int EM_SCROLL = 0xb5;
        internal const int EM_SCROLLCARET = 0xb7;
        public const int EM_SETCHARFORMAT = 0x444;
        internal const int EM_SETMARGINS = 0xd3;
        internal const int EM_SETMODIFY = 0xb9;
        internal const int EM_SETPASSWORDCHAR = 0xcc;
        internal const int EM_SETREADONLY = 0xcf;
        internal const int EM_SETSEL = 0xb1;
        internal const int EM_UNDO = 0xc7;
        internal const int ERROR_ACCESS_DENIED = 5;
        internal const int ERROR_ALREADY_EXISTS = 0xb7;
        internal const int ERROR_CANNOT_MAKE = 0x52;
        internal const int ERROR_CLASS_ALREADY_EXISTS = 0x582;
        internal const int ERROR_FILE_EXISTS = 80;
        internal const int ERROR_INSUFFICIENT_BUFFER = 0x7a;
        internal const int ERROR_INVALID_HANDLE = 6;
        public static long ERROR_INVALID_SERVICE_ACCOUNT = 0x421L;
        public static readonly int ERROR_MORE_DATA = 0xea;
        internal const int ERROR_NONE_MAPPED = 0x534;
        internal const int ERROR_NOT_CAPABLE = 0x307;
        internal const int ERROR_NOT_SAME_DEVICE = 0x11;
        public static long ERROR_SERVICE_DATABASE_LOCKED = 0x41fL;
        internal const int ERROR_SHARING_VIOLATION = 0x20;
        internal const int ERROR_SUCCESS = 0;
        internal const int FALSE = 0;
        internal const int FILE_PERSISTENT_ACLS = 8;
        internal const int FILE_TYPE_CHAR = 2;
        internal const int FLASHW_ALL = 3;
        internal const int FLASHW_CAPTION = 1;
        internal const int FLASHW_STOP = 0;
        internal const int FLASHW_TIMER = 4;
        internal const int FLASHW_TIMERNOFG = 12;
        internal const int FLASHW_TRAY = 2;
        private const int FO_COPY = 2;
        private const int FO_DELETE = 3;
        private const int FO_MOVE = 1;
        private const int FO_RENAME = 4;
        private const int FOF_ALLOWUNDO = 0x40;
        private const int FOF_CONFIRMMOUSE = 2;
        private const int FOF_FILESONLY = 0x80;
        private const int FOF_MULTIDESTFILES = 1;
        private const int FOF_NO_CONNECTED_ELEMENTS = 0x2000;
        private const int FOF_NOCONFIRMATION = 0x10;
        private const int FOF_NOCONFIRMMKDIR = 0x200;
        private const int FOF_NOCOPYSECURITYATTRIBS = 0x800;
        private const int FOF_NOERRORUI = 0x400;
        private const int FOF_NORECURSEREPARSE = 0x8000;
        private const int FOF_NORECURSION = 0x1000;
        private const int FOF_RENAMEONCOLLISION = 8;
        private const int FOF_SILENT = 4;
        private const int FOF_SIMPLEPROGRESS = 0x100;
        private const int FOF_WANTMAPPINGHANDLE = 0x20;
        private const int FOF_WANTNUKEWARNING = 0x4000;
        private const int FORMAT_MESSAGE_FROM_SYSTEM = 0x1000;
        private const int FSCTL_GET_COMPRESSION = 0x9003c;
        private const int FSCTL_SET_COMPRESSION = 0x9c040;
        public static int GENERIC_WRITE = 0x40000000;
        internal const int GW_CHILD = 5;
        internal const int GW_HWNDFIRST = 0;
        internal const int GW_HWNDLAST = 1;
        internal const int GW_HWNDNEXT = 2;
        internal const int GW_HWNDPREV = 3;
        internal const int GWL_EXSTYLE = -20;
        internal const int GWL_HWNDPARENT = -8;
        internal const int GWL_STYLE = -16;
        internal const int GWL_USERDATA = -21;
        internal const int HDF_IMAGE = 0x800;
        internal const int HDF_SORTDOWN = 0x200;
        internal const int HDF_SORTUP = 0x400;
        internal const int HDF_STRING = 0x4000;
        internal const int HDI_FORMAT = 4;
        internal const int HDI_WIDTH = 1;
        internal const int HDM_GETITEMRECT = 0x1207;
        internal const int HDM_SETIMAGELIST = 0x1208;
        internal const int HDM_SETITEM = 0x120c;
        internal const int HDN_BEGINTRACKA = -306;
        internal const int HDN_BEGINTRACKW = -326;
        internal const int HDN_ITEMCHANGEDA = -301;
        internal const int HDN_ITEMCHANGEDW = -321;
        internal const int HDN_ITEMCHANGINGA = -300;
        internal const int HDN_ITEMCHANGINGW = -320;
        internal const int HDS_HOTTRACK = 4;
        internal const int HTCAPTION = 2;
        internal const int HTCLOSE = 20;
        internal const int HTSYSMENU = 3;
        internal static readonly HandleRef HWND_BOTTOM = new HandleRef(null, (IntPtr)1);
        internal const int HWND_TOPMOST = -1;
        public const int ICON_BIG = 1;
        public const int ICON_SMALL = 0;
        internal const int IDOK = 1;
        internal static readonly IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1);
        internal const ushort KeyDownFlag = 0x80;
        internal const int LB_GETANCHORINDEX = 0x19d;
        internal const int LB_SETANCHORINDEX = 0x19c;
        internal const int LB_SETSEL = 0x185;
        internal const string LEGACY_RSAPRIVATE_BLOB = "CAPIPRIVATEBLOB";
        internal const string LEGACY_RSAPUBLIC_BLOB = "CAPIPUBLICBLOB";
        internal const uint LOAD_LIBRARY_AS_DATAFILE = 2;
        public static uint LOGON32_LOGON_NETWORK = 3;
        public static uint LOGON32_PROVIDER_DEFAULT = 0;
        public static uint LSA_POLICY_ALL_ACCESS = 0x1fff;
        internal const int LVCF_FMT = 1;
        internal const int LVCF_IMAGE = 0x10;
        internal const int LVCF_WIDTH = 2;
        internal const int LVCFMT_BITMAP_ON_RIGHT = 0x1000;
        internal const int LVCFMT_IMAGE = 0x800;
        internal const int LVCFMT_LEFT = 0;
        internal const int LVHT_ONITEM = 14;
        internal const int LVHT_ONITEMICON = 2;
        internal const int LVHT_ONITEMLABEL = 4;
        internal const int LVHT_ONITEMSTATEICON = 8;
        internal const int LVIF_STATE = 8;
        internal const int LVIR_BOUNDS = 0;
        internal const int LVIS_DROPHILITED = 8;
        internal const int LVIS_FOCUSED = 1;
        internal const int LVIS_SELECTED = 2;
        internal const int LVIS_STATEIMAGEMASK = 0xf000;
        internal const int LVM_DELETEALLITEMS = 0x1009;
        internal const int LVM_DELETEITEM = 0x1008;
        internal const int LVM_ENSUREVISIBLE = 0x1013;
        internal const int LVM_GETCOLUMNWIDTH = 0x101d;
        internal const int LVM_GETEDITCONTROL = 0x1018;
        internal const int LVM_GETHEADER = 0x101f;
        internal const int LVM_GETITEMCOUNT = 0x1004;
        internal const int LVM_GETITEMRECT = 0x100e;
        internal const int LVM_GETITEMSTATE = 0x102c;
        internal const int LVM_GETITEMW = 0x104b;
        internal const int LVM_GETNEXTITEM = 0x100c;
        internal const int LVM_GETSELECTIONMARK = 0x1042;
        internal const int LVM_GETTOOLTIPS = 0x104e;
        internal const int LVM_HITTEST = 0x1012;
        internal const int LVM_INSERTCOLUMNA = 0x101b;
        internal const int LVM_INSERTCOLUMNW = 0x1061;
        internal const int LVM_INSERTITEMA = 0x1007;
        internal const int LVM_INSERTITEMW = 0x104d;
        internal const int LVM_SETCOLUMN = 0x101a;
        internal const int LVM_SETEXTENDEDLISTVIEWSTYLE = 0x1036;
        internal const int LVM_SETIMAGELIST = 0x1003;
        internal const int LVM_SETITEMSTATE = 0x102b;
        internal const int LVM_SETSELECTIONMARK = 0x1043;
        internal const int LVN_KEYDOWN = -155;
        internal const int LVS_EX_CHECKBOXES = 4;
        internal const int LVS_ILNORMAL = 0;
        internal const int LVS_ILSMALL = 1;
        internal const int MA_ACTIVATE = 1;
        internal const int MA_ACTIVATEANDEAT = 2;
        internal const int MA_NOACTIVATE = 3;
        internal const int MA_NOACTIVATEANDEAT = 4;
        internal const int MAX_PATH = 260;
        internal const int MF_BYCOMMAND = 0;
        internal const int MF_DISABLED = 2;
        internal const int MF_ENABLED = 0;
        internal const int MF_GRAYED = 1;
        internal const int NM_CLICK = -2;
        internal const int NM_DBLCLK = -3;
        internal const int NO_ERROR = 0;
        internal static readonly int NTE_BAD_KEYSET = -2146893802;
        internal const int NTE_BAD_SIGNATURE = -2146893818;
        internal const int NTE_BUFFER_TOO_SMALL = -2146893784;
        internal static readonly int NTE_SILENT_CONTEXT = -2146893790;
        internal const uint OFN_ALLOWMULTISELECT = 0x200;
        internal const uint OFN_CREATEPROMPT = 0x2000;
        internal const uint OFN_DONTADDTORECENT = 0x2000000;
        internal const uint OFN_ENABLEHOOK = 0x20;
        internal const uint OFN_ENABLEINCLUDENOTIFY = 0x400000;
        internal const uint OFN_ENABLESIZING = 0x800000;
        internal const uint OFN_ENABLETEMPLATE = 0x40;
        internal const uint OFN_ENABLETEMPLATEHANDLE = 0x80;
        internal const uint OFN_EX_NOPLACESBAR = 1;
        internal const uint OFN_EXPLORER = 0x80000;
        internal const uint OFN_EXTENSIONDIFFERENT = 0x400;
        internal const uint OFN_FILEMUSTEXIST = 0x1000;
        internal const uint OFN_FORCESHOWHIDDEN = 0x10000000;
        internal const uint OFN_HIDEREADONLY = 4;
        internal const uint OFN_LONGNAMES = 0x200000;
        internal const uint OFN_NOCHANGEDIR = 8;
        internal const uint OFN_NODEREFERENCELINKS = 0x100000;
        internal const uint OFN_NOLONGNAMES = 0x40000;
        internal const uint OFN_NONETWORKBUTTON = 0x20000;
        internal const uint OFN_NOREADONLYRETURN = 0x8000;
        internal const uint OFN_NOTESTFILECREATE = 0x10000;
        internal const uint OFN_NOVALIDATE = 0x100;
        internal const uint OFN_OVERWRITEPROMPT = 2;
        internal const uint OFN_PATHMUSTEXIST = 0x800;
        internal const uint OFN_READONLY = 1;
        internal const uint OFN_SHAREAWARE = 0x4000;
        internal const uint OFN_SHOWHELP = 0x10;
        internal const int PENDINGMSG_WAITDEFPROCESS = 2;
        internal const int PM_NOREMOVE = 0;
        internal const int PM_NOYIELD = 2;
        internal const int PM_REMOVE = 1;
        internal const byte PRIVATEKEYBLOB = 7;
        internal const int PSHHELP = 0x40e;
        internal const byte PUBLICKEYBLOB = 6;
        public static int READ_CONTROL = 0x20000;
        internal const int SB_HORZ = 0;
        internal const int SC_CLOSE = 0xf060;
        internal const int SC_CONTEXTHELP = 0xf180;
        internal const int SC_RESTORE = 0xf120;
        internal static readonly int SCARD_E_NO_SMARTCARD = -2146435060;
        public const int SCF_ALL = 4;
        public const int SCF_SELECTION = 1;
        internal const int SERVERCALL_ISHANDLED = 0;
        public static int SERVICE_AUTO_START = 2;
        public static int SERVICE_ERROR_NORMAL = 1;
        public static uint SERVICE_NO_CHANGE = uint.MaxValue;
        public static int SERVICE_WIN32_OWN_PROCESS = 0x10;
        internal const int SHACF_AUTOAPPEND_FORCE_ON = 0x40000000;
        internal const int SHACF_AUTOSUGGEST_FORCE_ON = 0x10000000;
        internal const int SHACF_FILESYS_DIRS = 0x20;
        internal const int SHACF_FILESYSTEM = 1;
        internal const int SHACF_USETAB = 8;
        internal const int SHELL_NO_REGISTERED_APP_FOR_FILE_OR_VERB = 0x1f;
        internal const int ShgfiIcon = 0x100;
        internal const int ShgfiLargeIcon = 0;
        internal const int ShgfiOpenIcon = 2;
        internal const int ShgfiSelected = 0x10000;
        internal const int ShgfiShellIconSize = 4;
        internal const int ShgfiSmallIcon = 1;
        internal const int ShgfiSysIconIndex = 0x4000;
        internal const int ShgfiTypeName = 0x400;
        internal const int ShgfiUseFileAttributes = 0x10;
        internal const int SPI_GETFOREGROUNDFLASHCOUNT = 0x2004;
        public static int STANDARD_RIGHTS_REQUIRED = 0xf0000;
        internal const int STD_ERROR_HANDLE = -12;
        internal const int STD_INPUT_HANDLE = -10;
        internal const int STD_OUTPUT_HANDLE = -11;
        public const int STGM_CONVERT = 0x20000;
        public const int STGM_CREATE = 0x1000;
        public const int STGM_DELETEONRELEASE = 0x4000000;
        public const int STGM_DIRECT = 0;
        public const int STGM_DIRECT_SWMR = 0x400000;
        public const int STGM_FAILIFTHERE = 0;
        public const int STGM_NOSCRATCH = 0x100000;
        public const int STGM_NOSNAPSHOT = 0x200000;
        public const int STGM_PRIORITY = 0x40000;
        public const int STGM_READ = 0;
        public const int STGM_READWRITE = 2;
        public const int STGM_SHARE_DENY_NONE = 0x40;
        public const int STGM_SHARE_DENY_READ = 0x30;
        public const int STGM_SHARE_DENY_WRITE = 0x20;
        public const int STGM_SHARE_EXCLUSIVE = 0x10;
        public const int STGM_SIMPLE = 0x8000000;
        public const int STGM_TRANSACTED = 0x10000;
        public const int STGM_WRITE = 1;
        internal const int SW_SHOW = 5;
        internal const int SW_SHOWNA = 8;
        internal const int SW_SHOWNOACTIVATE = 4;
        internal const int SW_SHOWNORMAL = 1;
        internal const int SWP_NOACTIVATE = 0x10;
        internal const int SWP_NOMOVE = 2;
        internal const int SWP_NOSIZE = 1;
        internal const int SYSTEM_FONT = 13;
        internal const int TRUE = 1;
        public const int TTDT_AUTOPOP = 2;
        public const int TTM_POP = 0x41c;
        public const int TTM_SETDELAYTIME = 0x403;
        public const int TTN_GETDISPINFOW = -530;
        internal const int TV_FIRST = 0x1100;
        internal const int TVGN_CARET = 9;
        internal const int TVGN_DROPHILITE = 8;
        internal const int TVHitOnItemIcon = 2;
        internal const int TVHitOnItemLabel = 4;
        internal const int TVHitOnItemStateIcon = 0x40;
        internal const int TVIF_HANDLE = 0x10;
        internal const int TVIF_STATE = 8;
        internal const int TVIS_STATEIMAGEMASK = 0xf000;
        internal const int TVM_GETEDITCONTROL = 0x110f;
        internal const int TVM_GETEXTENDEDSTYLE = 0x112d;
        internal const int TVM_GETTOOLTIPS = 0x1119;
        internal const int TVM_HITTEST = 0x1111;
        internal const int TVM_SELECTITEM = 0x110b;
        internal const int TVM_SETEXTENDEDSTYLE = 0x112c;
        internal const int TVM_SETIMAGELIST = 0x1109;
        internal const int TVM_SETITEM = 0x110d;
        internal const int TVS_EX_DOUBLEBUFFER = 4;
        internal const int TVS_EX_FADEINOUTEXPANDOS = 0x40;
        internal const int TVSIL_STATE = 2;
        internal const int UIS_CLEAR = 2;
        internal const int UIS_INITIALIZE = 3;
        internal const int UIS_SET = 1;
        internal const int UISF_HIDEACCEL = 2;
        internal const int UISF_HIDEFOCUS = 1;
        internal const int VK_CONTROL = 0x11;
        internal const int VK_DELETE = 0x2e;
        internal const int VK_ESCAPE = 0x1b;
        internal const int VK_MENU = 0x12;
        internal const int VK_RETURN = 13;
        internal const int VK_SHIFT = 0x10;
        internal const int WM_CANCELMODE = 0x1f;
        internal const int WM_CHAR = 0x102;
        internal const int WM_CLOSE = 0x10;
        internal const int WM_COMMAND = 0x111;
        internal const int WM_CONTEXTMENU = 0x7b;
        internal const int WM_COPY = 0x301;
        internal const int WM_CUT = 0x300;
        internal const int WM_DESTROY = 2;
        internal const int WM_DISPLAYCHANGE = 0x7e;
        internal const int WM_ENABLE = 10;
        public const int WM_ENDSESSION = 0x16;
        internal const int WM_ERASEBKGND = 20;
        internal const int WM_GETDLGCODE = 0x87;
        internal const int WM_HELP = 0x53;
        internal const int WM_HSCROLL = 0x114;
        internal const int WM_INITDIALOG = 0x110;
        internal const int WM_KEYDOWN = 0x100;
        internal const int WM_KEYUP = 0x101;
        internal const int WM_KILLFOCUS = 8;
        internal const int WM_LBUTTONDBLCLK = 0x203;
        internal const int WM_LBUTTONDOWN = 0x201;
        internal const int WM_LBUTTONUP = 0x202;
        internal const int WM_MBUTTONDBLCLK = 0x209;
        internal const int WM_MBUTTONDOWN = 0x207;
        internal const int WM_MBUTTONUP = 520;
        internal const int WM_MOUSEACTIVATE = 0x21;
        internal const int WM_MOUSELAST = 0x20a;
        internal const int WM_MOUSEMOVE = 0x200;
        internal const int WM_MOUSEWHEEL = 0x20a;
        internal const int WM_NCLBUTTONDOWN = 0xa1;
        internal const int WM_NCMBUTTONDBLCLK = 0xa9;
        internal const int WM_NCMOUSEMOVE = 160;
        internal const int WM_NCPAINT = 0x85;
        internal const int WM_NOTIFY = 0x4e;
        internal const int WM_PAINT = 15;
        internal const int WM_PALETTECHANGED = 0x311;
        internal const int WM_PASTE = 770;
        public const int WM_QUERYENDSESSION = 0x11;
        internal const int WM_RBUTTONDBLCLK = 0x206;
        internal const int WM_RBUTTONDOWN = 0x204;
        internal const int WM_RBUTTONUP = 0x205;
        internal const int WM_REFLECT = 0x2000;
        internal const int WM_SETFOCUS = 7;
        public const int WM_SETFONT = 0x30;
        public const int WM_SETICON = 0x80;
        internal const int WM_SETREDRAW = 11;
        internal const int WM_SETTEXT = 12;
        internal const int WM_SETTINGCHANGE = 0x1a;
        internal const int WM_SIZE = 5;
        internal const int WM_STYLECHANGED = 0x7d;
        internal const int WM_SYSCHAR = 0x106;
        internal const int WM_SYSCOLORCHANGE = 0x15;
        internal const int WM_SYSCOMMAND = 0x112;
        internal const int WM_SYSKEYDOWN = 260;
        internal const int WM_SYSKEYUP = 0x105;
        internal const int WM_TIMER = 0x113;
        internal const int WM_UNDO = 0x304;
        internal const int WM_UPDATEUISTATE = 0x128;
        internal const int WM_USER = 0x400;
        internal const int WM_VSCROLL = 0x115;
        internal const int WM_WINDOWPOSCHANGED = 0x47;
        internal const int WM_WINDOWPOSCHANGING = 70;
        internal const int WM_XBUTTONDBLCLK = 0x20d;
        internal const int WM_XBUTTONDOWN = 0x20b;
        internal const int WM_XBUTTONUP = 0x20c;
        public static int WRITE_DAC = 0x40000;
        public static int WRITE_OWNER = 0x80000;
        internal const int WS_BORDER = 0x800000;
        internal const int WS_CAPTION = 0xc00000;
        internal const int WS_CHILD = 0x40000000;
        internal const int WS_EX_CLIENTEDGE = 0x200;
        public const int WS_EX_CONTEXTHELP = 0x400;
        public const int WS_EX_CONTROLPARENT = 0x10000;
        public const int WS_EX_DLGMODALFRAME = 1;
        internal const int WS_EX_RIGHT = 0x1000;
        internal const int WS_EX_TOOLWINDOW = 0x80;
        internal const int WS_EX_TOPMOST = 8;
        public const int WS_MAXIMIZEBOX = 0x10000;
        public const int WS_MINIMIZEBOX = 0x20000;
        internal const int WS_OVERLAPPED = 0;
        internal const int WS_POPUP = -2147483648;
        internal const int WS_VISIBLE = 0x10000000;

        // Methods
        static NativeMethods()
        {
            if (Marshal.SystemDefaultCharSize == 1)
            {
                BFFM_SETSELECTION = 0x466;
            }
            else
            {
                BFFM_SETSELECTION = 0x467;
            }
        }

        [DllImport("user32", EntryPoint = "WindowFromPoint", CharSet = CharSet.Auto, ExactSpelling = true)]
        private static extern IntPtr _WindowFromPoint(POINTSTRUCT pt);
        public static unsafe byte[] AccountToSid(string account)
        {
            uint sidSize = 0x200;
            byte[] sourceArray = new byte[sidSize];
            uint domainLength = 0x200;
            StringBuilder domainName = new StringBuilder((int)domainLength);
            fixed (byte* numRef = sourceArray)
            {
                AccountType type;
                if (!LookupAccountName(null, account, (void*)numRef, ref sidSize, domainName, ref domainLength, out type))
                {
                    throw new Win32Exception(Marshal.GetLastWin32Error());
                }
                sidSize = GetLengthSid((void*)numRef);
            }
            domainName.ToString();
            byte[] destinationArray = new byte[sidSize];
            Array.Copy(sourceArray, destinationArray, (long)sidSize);
            return destinationArray;
        }

        [DllImport("kernel32.dll")]
        internal static extern bool AssignProcessToJobObject(SafeHandle hJob, SafeHandle hProcess);
        [DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
        public static extern int ChangeServiceConfig(ServiceHandle serviceHandle, uint type, uint startType, uint errorControl, string binaryPathName, string loadOrderGroup, string tagId, string dependencies, string accountName, string password, string displayName);
        [DllImport("advapi32.dll", SetLastError = true)]
        public static extern int ChangeServiceConfig2(ServiceHandle serviceHandle, ServiceConfig2InfoLevel dwInfoLevel, IntPtr lpInfo);
        [DllImport("kernel32", SetLastError = true)]
        internal static extern bool CloseHandle(IntPtr handle);
        [DllImport("advapi32.dll", SetLastError = true)]
        public static extern bool CloseServiceHandle(IntPtr handle);
        [DllImport("ole32", ExactSpelling = true)]
        internal static extern int CoRegisterMessageFilter(IOleMessageFilter newFilter, ref IntPtr oldMsgFilter);
        [DllImport("ole32", ExactSpelling = true)]
        internal static extern int CoRegisterMessageFilter(HandleRef handle, ref IntPtr oldMsgFilter);
        [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
        internal static extern SafeFileHandle CreateFile(string lpFileName, [MarshalAs(UnmanagedType.U4)] FileAccess dwDesiredAccess, [MarshalAs(UnmanagedType.U4)] FileShare dwShareMode, IntPtr lpSecurityAttributes, [MarshalAs(UnmanagedType.U4)] CreationDisposition dwCreationDisposition, [MarshalAs(UnmanagedType.U4)] FileAttributes dwFlagsAndAttributes, IntPtr hTemplateFile);
        [DllImport("ole32.dll", PreserveSig = false)]
        public static extern ILockBytes CreateILockBytesOnHGlobal(IntPtr hGlobal, bool fDeleteOnRelease);
        [DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
        internal static extern IntPtr CreateJobObject([In] ref SECURITY_ATTRIBUTES lpJobAttributes, string lpName);
        [DllImport("user32", CharSet = CharSet.Unicode, SetLastError = true)]
        internal static extern IntPtr CreateWindowEx(int dwExStyle, string lpszClassName, string lpszWindowName, int style, int x, int y, int width, int height, IntPtr hWndParent, IntPtr hMenu, IntPtr hInst, [MarshalAs(UnmanagedType.AsAny)] object pvParam);
        [DllImport("advapi32.dll")]
        public static extern void CredFree(IntPtr buffer);
        [DllImport("credui.dll", CharSet = CharSet.Unicode, SetLastError = true)]
        public static extern bool CredPackAuthenticationBuffer(int dwFlags, string pszUserName, string pszPassword, byte[] pPackedCredentials, ref uint pcbPackedCredentials);
        [DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
        public static extern bool CredRead(string targetName, uint type, uint flags, out IntPtr credential);
        [DllImport("credui.dll", CharSet = CharSet.Unicode)]
        public static extern int CredUIParseUserName(string pszUserName, StringBuilder pszUser, uint ulUserMaxChars, StringBuilder pszDomain, uint ulDomainMaxChars);
        [DllImport("credui.dll", CharSet = CharSet.Unicode)]
        public static extern int CredUIPromptForCredentials(ref CREDUI_INFO pUiInfo, string pszTargetName, IntPtr reserved, int dwAuthError, StringBuilder pszUserName, uint ulUserNameMaxChars, StringBuilder pszPassword, uint ulPasswordMaxChars, ref bool pfSave, int dwFlags);
        [DllImport("credui.dll", CharSet = CharSet.Unicode)]
        public static extern int CredUIPromptForWindowsCredentials(ref CREDUI_INFO pUiInfo, int dwAuthError, ref uint pulAuthPackage, byte[] pvInAuthBuffer, uint ulInAuthBufferSize, out IntPtr ppvOutAuthBuffer, out uint pulOutAuthBufferSize, ref bool pfSave, int dwFlags);
        [DllImport("credui.dll", CharSet = CharSet.Unicode, SetLastError = true)]
        public static extern bool CredUnPackAuthenticationBuffer(int dwFlags, IntPtr pAuthBuffer, uint cbAuthBuffer, StringBuilder pszUserName, ref uint pcchMaxUserName, StringBuilder pszDomainName, ref uint pcchMaxDomainName, StringBuilder pszPassword, ref uint pcchMaxPassword);
        [DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
        public static extern bool CredWrite(ref CREDENTIAL credential, uint flags);
        [return: MarshalAs(UnmanagedType.Bool)]
        [DllImport("crypt32.dll", SetLastError = true)]
        internal static extern bool CryptAcquireCertificatePrivateKey(IntPtr pCert, int dwFlags, IntPtr pvReserved, out IntPtr phCryptProvOrNCryptKey, out uint dwKeySpec, [MarshalAs(UnmanagedType.Bool)] out bool pfCallerFreeProvOrNCryptKey);
        [DllImport("advapi32.dll", SetLastError = true)]
        internal static extern int CryptReleaseContext(IntPtr hProv, int dwFlags);
        [DllImport("gdi32")]
        internal static extern bool DeleteObject(IntPtr hObject);
        [DllImport("user32")]
        internal static extern bool DestroyIcon(IntPtr hIcon);
        [DllImport("user32", CharSet = CharSet.Unicode, SetLastError = true)]
        internal static extern bool DestroyWindow(IntPtr hWnd);
        [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern bool DeviceIoControl(SafeHandle hDevice, uint dwIoControlCode, IntPtr lpInBuffer, uint nInBufferSize, out short lpOutBuffer, uint nOutBufferSize, out uint lpBytesReturned, IntPtr lpOverlapped);
        [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern bool DeviceIoControl(SafeHandle hDevice, uint dwIoControlCode, ref short lpInBuffer, uint nInBufferSize, IntPtr lpOutBuffer, uint nOutBufferSize, out uint lpBytesReturned, IntPtr lpOverlapped);
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        internal static extern IntPtr DispatchMessage(ref MSG msg);
        public static string DnsHostnameToComputerName(string hostname)
        {
            StringBuilder computerName = new StringBuilder(0x400);
            int capacity = computerName.Capacity;
            if (DnsHostnameToComputerName(hostname, computerName, ref capacity) != 0)
            {
                return computerName.ToString();
            }
            return null;
        }

        [DllImport("Kernel32.dll", EntryPoint = "DnsHostnameToComputerNameW", CharSet = CharSet.Unicode, SetLastError = true)]
        public static extern int DnsHostnameToComputerName(string hostname, StringBuilder computerName, ref int size);
        [DllImport("user32", CharSet = CharSet.Unicode, SetLastError = true)]
        public static extern int DrawTextExW(IntPtr hDC, StringBuilder lpszString, int nCount, ref RECT lpRect, int nFormat, [In, Out] DRAWTEXTPARAMS lpDTParams);
        [DllImport("ntdsapi.dll", CharSet = CharSet.Unicode)]
        internal static extern uint DsBind(string DomainControllerName, string DnsDomainName, out IntPtr phDS);
        public static DS_NAME_RESULT_ITEM[] DsCrackNames(IntPtr hDS, DS_NAME_FLAGS flags, DS_NAME_FORMAT formatOffered, DS_NAME_FORMAT formatDesired, string[] names)
        {
            IntPtr ptr;
            DS_NAME_RESULT_ITEM[] ds_name_result_itemArray;
            uint num = DsCrackNames(hDS, flags, formatOffered, formatDesired, (names == null) ? 0 : ((uint)names.Length), names, out ptr);
            if (num != 0)
            {
                throw new Win32Exception((int)num);
            }
            try
            {
                DS_NAME_RESULT ds_name_result = new DS_NAME_RESULT
                {
                    cItems = (uint)Marshal.ReadInt32(ptr),
                    rItems = Marshal.ReadIntPtr(ptr, Marshal.OffsetOf(typeof(DS_NAME_RESULT), "rItems").ToInt32())
                };
                IntPtr rItems = ds_name_result.rItems;
                ds_name_result_itemArray = new DS_NAME_RESULT_ITEM[ds_name_result.cItems];
                for (int i = 0; i < ds_name_result.cItems; i++)
                {
                    ds_name_result_itemArray[i] = (DS_NAME_RESULT_ITEM)Marshal.PtrToStructure(rItems, typeof(DS_NAME_RESULT_ITEM));
                    rItems = (IntPtr)(((long)rItems) + Marshal.SizeOf(ds_name_result_itemArray[i]));
                }
            }
            finally
            {
                DsFreeNameResult(ptr);
            }
            return ds_name_result_itemArray;
        }

        [DllImport("ntdsapi.dll", CharSet = CharSet.Auto)]
        public static extern uint DsCrackNames(IntPtr hDS, DS_NAME_FLAGS flags, DS_NAME_FORMAT formatOffered, DS_NAME_FORMAT formatDesired, uint cNames, [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.LPWStr, SizeParamIndex = 4)] string[] rpNames, out IntPtr ppResult);
        [DllImport("ntdsapi.dll", CharSet = CharSet.Auto)]
        internal static extern void DsFreeNameResult(IntPtr pResult);
        [DllImport("Netapi32.dll", CharSet = CharSet.Unicode)]
        internal static extern uint DsGetSiteName(string ComputerName, out string SiteName);
        [DllImport("ntdsapi.dll", CharSet = CharSet.Unicode)]
        public static extern uint DsUnBind(ref IntPtr phDS);
        [DllImport("user32.dll", SetLastError = true)]
        internal static extern bool EnableMenuItem(HandleRef hMenu, uint uIDEnableItem, uint uEnable);
        [DllImport("user32", ExactSpelling = true)]
        internal static extern bool EnableWindow(IntPtr hWnd, bool bEnable);
        [DllImport("user32", CharSet = CharSet.Auto, ExactSpelling = true)]
        internal static extern int EnumChildWindows(IntPtr hWndParent, EnumWindowsProc lpEnumFunc, IntPtr lParam);
        [DllImport("user32", CharSet = CharSet.Auto, ExactSpelling = true)]
        internal static extern int EnumThreadWindows(uint dwThreadId, EnumWindowsProc lpEnumFunc, IntPtr lParam);
        [DllImport("user32", CharSet = CharSet.Auto, ExactSpelling = true)]
        internal static extern int EnumWindows(EnumWindowsProc lpEnumFunc, IntPtr lParam);
        [DllImport("user32", CharSet = CharSet.Auto, SetLastError = true)]
        internal static extern int FlashWindowEx(ref FLASHWINFO fwi);
        internal static string FormatError(int number)
        {
            uint dwMessageId = (uint)number;
            StringBuilder lpBuffer = new StringBuilder(0x400);
            FormatMessage(0x1000, IntPtr.Zero, dwMessageId, 0, lpBuffer, lpBuffer.Capacity, IntPtr.Zero);
            return lpBuffer.ToString();
        }

        [DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
        private static extern int FormatMessage(uint dwFlags, IntPtr lpSource, uint dwMessageId, int dwLanguageId, [Out] StringBuilder lpBuffer, int nSize, IntPtr Arguments);
        [DllImport("kernel32.dll", SetLastError = true)]
        internal static extern bool FreeLibrary(IntPtr hModule);
        [DllImport("advapi32.dll")]
        public static extern uint GetAclInformation(IntPtr acl, ref ACL_SIZE_INFORMATION aclInformation, uint aclInformationLength, ACL_INFORMATION_CLASS aclInformationClass);
        [DllImport("user32", CharSet = CharSet.Auto, SetLastError = true)]
        internal static extern IntPtr GetActiveWindow();
        [DllImport("user32", CharSet = CharSet.Auto, ExactSpelling = true)]
        internal static extern IntPtr GetAncestor(HandleRef window, GetAncestorFlags flags);
        [DllImport("user32", CharSet = CharSet.Auto, ExactSpelling = true)]
        internal static extern int GetCaretPos(ref POINT lpPoint);
        internal static string GetClassName(IntPtr hwnd)
        {
            StringBuilder lpClassName = new StringBuilder(0x100);
            GetClassName(hwnd, lpClassName, lpClassName.Capacity);
            return lpClassName.ToString();
        }

        [DllImport("User32", CharSet = CharSet.Unicode, SetLastError = true)]
        private static extern int GetClassName(IntPtr hwnd, StringBuilder lpClassName, int nMaxCount);
        [DllImport("user32", CharSet = CharSet.Auto)]
        internal static extern int GetClientRect(IntPtr hWnd, ref RECT rc);
        [DllImport("user32")]
        internal static extern bool GetClientRect(HandleRef hwnd, out RECT rect);
        [DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
        internal static extern IntPtr GetComboBoxInfo(HandleRef hWnd, COMBOBOXINFO pComboboxInfo);
        public static string GetComputerNameEx(COMPUTER_NAME_FORMAT format)
        {
            StringBuilder nameBuffer = new StringBuilder(0x400);
            int capacity = nameBuffer.Capacity;
            int num2 = GetComputerNameEx((int)format, nameBuffer, ref capacity);
            int num3 = Marshal.GetLastWin32Error();
            if ((num2 == 0) && (num3 == ERROR_MORE_DATA))
            {
                nameBuffer.Capacity = capacity + 1;
                capacity = nameBuffer.Capacity;
                num2 = GetComputerNameEx((int)format, nameBuffer, ref capacity);
            }
            if (num2 != 0)
            {
                return nameBuffer.ToString();
            }
            return null;
        }

        [DllImport("Kernel32.dll", EntryPoint = "GetComputerNameExW", CharSet = CharSet.Unicode, SetLastError = true)]
        public static extern int GetComputerNameEx(int nameType, StringBuilder nameBuffer, ref int bufferSize);
        [DllImport("kernel32", CharSet = CharSet.Auto, SetLastError = true)]
        internal static extern IntPtr GetConsoleWindow();
        [DllImport("kernel32.dll")]
        internal static extern int GetCurrentThreadId();
        [DllImport("user32", CharSet = CharSet.Auto, ExactSpelling = true)]
        public static extern IntPtr GetDC(IntPtr hWnd);
        [DllImport("user32", CharSet = CharSet.Auto)]
        internal static extern IntPtr GetDlgItem(HandleRef hWndDlg, int Id);
        internal static short GetFileCompression(SafeHandle handle)
        {
            short num;
            uint lpBytesReturned = 0;
            if (!DeviceIoControl(handle, 0x9003c, IntPtr.Zero, 0, out num, 2, out lpBytesReturned, IntPtr.Zero))
            {
                throw new Win32Exception();
            }
            return num;
        }

        [DllImport("kernel32", SetLastError = true)]
        internal static extern int GetFileType(IntPtr handle);
        [DllImport("user32", CharSet = CharSet.Auto, ExactSpelling = true)]
        internal static extern IntPtr GetFocus();
        [DllImport("user32", SetLastError = true)]
        internal static extern IntPtr GetForegroundWindow();
        [DllImport("OLE32.DLL", CharSet = CharSet.Auto, PreserveSig = false)]
        public static extern IntPtr GetHGlobalFromILockBytes(ILockBytes pLockBytes);
        [DllImport("User32.dll")]
        internal static extern ushort GetKeyState(short key);
        [DllImport("Advapi32.dll", CallingConvention = CallingConvention.StdCall, SetLastError = true, ExactSpelling = true)]
        private static extern unsafe uint GetLengthSid(void* pSid);
        internal static int GetListViewColumnWidth(HandleRef hwnd, int column)
        {
            return (int)SendMessage(hwnd, 0x101d, (IntPtr)column, IntPtr.Zero);
        }

        internal static string GetModuleFileName()
        {
            return GetModuleFileName(IntPtr.Zero);
        }

        internal static string GetModuleFileName(IntPtr hModule)
        {
            StringBuilder lpFilename = new StringBuilder(260);
            int num = GetModuleFileName(hModule, lpFilename, lpFilename.Capacity);
            int number = Marshal.GetLastWin32Error();
            if ((num == 0) || (num >= lpFilename.Capacity))
            {
                throw new TeamFoundationServerException(FormatError(number));
            }
            return lpFilename.ToString();
        }

        [DllImport("kernel32", CharSet = CharSet.Unicode, SetLastError = true)]
        private static extern int GetModuleFileName(IntPtr hModule, StringBuilder lpFilename, int nSize);
        [DllImport("kernel32", CharSet = CharSet.Unicode)]
        internal static extern IntPtr GetModuleHandle(string modName);
        [DllImport("advapi32.dll", CharSet = CharSet.Unicode)]
        public static extern uint GetNamedSecurityInfo(string objectName, ResourceType objectType, SecurityInfos securityInfo, out IntPtr sidOwner, out IntPtr sidGroup, out IntPtr dacl, out IntPtr sacl, out IntPtr securityDescriptor);
        [DllImport("kernel32.dll")]
        public static extern void GetNativeSystemInfo(ref SYSTEM_INFO lpSystemInfo);
        [DllImport("comdlg32.dll", CharSet = CharSet.Unicode)]
        internal static extern bool GetOpenFileName(ref OPENFILENAME ofn);
        [DllImport("user32", CharSet = CharSet.Auto, ExactSpelling = true)]
        internal static extern IntPtr GetParent(IntPtr window);
        [DllImport("user32", CharSet = CharSet.Auto, ExactSpelling = true)]
        internal static extern IntPtr GetParent(HandleRef window);
        [DllImport("Kernel32.dll")]
        internal static extern bool GetProductInfo(int osMajorVersion, int osMinorVersion, int spMajorVersion, int spMinorVersion, out int edition);
        [DllImport("kernel32", SetLastError = true)]
        internal static extern IntPtr GetStdHandle(int nStdHandle);
        [DllImport("gdi32", CharSet = CharSet.Auto, ExactSpelling = true)]
        internal static extern IntPtr GetStockObject(int nIndex);
        [DllImport("kernel32", SetLastError = true)]
        internal static extern ushort GetSystemDefaultLangID();
        [DllImport("user32.dll", SetLastError = true)]
        internal static extern IntPtr GetSystemMenu(HandleRef hwnd, bool bRevert);
        internal static string GetTempFileName(string tmpPath, string prefix, uint uniqueIdOrZero)
        {
            StringBuilder tmpFileName = new StringBuilder(260);
            if (GetTempFileName(tmpPath, prefix, uniqueIdOrZero, tmpFileName) == 0)
            {
                throw new IOException("Error Creating Temp File."/*CommonResources.ErrorCreatingTempFile(tmpPath)*/);
            }
            return tmpFileName.ToString();
        }

        [DllImport("kernel32", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern uint GetTempFileName(string tmpPath, string prefix, uint uniqueIdOrZero, StringBuilder tmpFileName);
        [DllImport("Kernel32.dll", EntryPoint = "GetVersionExW", CharSet = CharSet.Unicode, SetLastError = true)]
        private static extern bool GetVersionEx([In, Out] OSVersionInfoEx ver);
        [DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
        internal static extern bool GetVolumeInformation(string lpRootPathName, StringBuilder lpVolumeNameBuffer, int nVolumeNameSize, out uint lpVolumeSerialNumber, out uint lpMaximumComponentLength, out uint lpFileSystemFlags, StringBuilder lpFileSystemNameBuffer, int nFileSystemNameSize);
        [DllImport("user32", CharSet = CharSet.Auto, ExactSpelling = true)]
        internal static extern IntPtr GetWindow(IntPtr hWnd, int wCmd);
        [DllImport("user32", CharSet = CharSet.Auto, ExactSpelling = true)]
        internal static extern IntPtr GetWindow(HandleRef hWnd, int uCmd);
        [DllImport("user32", CharSet = CharSet.Auto, ExactSpelling = true)]
        internal static extern IntPtr GetWindowDC(HandleRef hwnd);
        [DllImport("user32", CharSet = CharSet.Auto)]
        internal static extern IntPtr GetWindowLong(IntPtr hWnd, int nIndex);
        [DllImport("user32", CharSet = CharSet.Auto)]
        internal static extern IntPtr GetWindowLong(HandleRef hWnd, int nIndex);
        [DllImport("user32")]
        internal static extern bool GetWindowRect(HandleRef hwnd, out RECT rect);
        [DllImport("user32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
        internal static extern int GetWindowText(IntPtr hWnd, [Out] StringBuilder lpString, int nMaxCount);
        internal static Guid GuidFromNativePtr(IntPtr pguid)
        {
            StringBuilder lpsz = new StringBuilder(0x40);
            StringFromGUID2(pguid, lpsz, lpsz.Capacity);
            return new Guid(lpsz.ToString());
        }

        [DllImport("comctl32.dll", CharSet = CharSet.Auto)]
        internal static extern int ImageList_Add(IntPtr hImageList, IntPtr bmImage, IntPtr bmMask);
        [DllImport("comctl32", CharSet = CharSet.Unicode)]
        internal static extern IntPtr ImageList_Duplicate(IntPtr himageListSource);
        [DllImport("comctl32.dll", CharSet = CharSet.Auto)]
        internal static extern IntPtr ImageList_GetIcon(IntPtr hImageList, int index, uint flags);
        [DllImport("comctl32")]
        internal static extern int ImageList_GetIconSize(IntPtr himage, out int cx, out int cy);
        [DllImport("comctl32.dll", CharSet = CharSet.Auto)]
        internal static extern int ImageList_GetImageCount(IntPtr hImageList);
        [DllImport("comctl32.dll", CharSet = CharSet.Auto)]
        internal static extern bool ImageList_GetImageInfo(IntPtr hImageList, int index, ref IMAGEINFO imageInfo);
        [DllImport("comctl32.dll", CharSet = CharSet.Auto)]
        internal static extern int ImageList_ReplaceIcon(IntPtr hImageList, int index, IntPtr hicon);
        [DllImport("user32", CharSet = CharSet.Auto, ExactSpelling = true)]
        internal static extern bool InvalidateRect(HandleRef hWnd, ref RECT rect, bool erase);
        [DllImport("user32", CharSet = CharSet.Auto, ExactSpelling = true)]
        internal static extern bool IsChild(IntPtr hWndParent, IntPtr hWnd);
        [DllImport("user32")]
        internal static extern bool IsWindow(IntPtr hwnd);
        [DllImport("user32", ExactSpelling = true)]
        internal static extern bool IsWindowEnabled(IntPtr hWnd);
        [DllImport("user32")]
        internal static extern bool IsWindowVisible(IntPtr hwnd);
        [return: MarshalAs(UnmanagedType.Bool)]
        [DllImport("kernel32.dll")]
        public static extern bool IsWow64Process([In] IntPtr hProcess, out bool lpSystemInfo);
        [DllImport("user32")]
        internal static extern bool KillTimer(HandleRef hwnd, int idEvent);
        [DllImport("user32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
        internal static extern int LoadString(IntPtr hInstance, uint uID, [Out] StringBuilder lpBuffer, int nBufferMax);
        [DllImport("kernel32.dll")]
        public static extern IntPtr LocalFree(IntPtr handle);
        [DllImport("advapi32.dll", SetLastError = true)]
        public static extern IntPtr LockServiceDatabase(IntPtr handle);
        [DllImport("advapi32.dll", CharSet = CharSet.Unicode)]
        public static extern int LogonUser(string userName, string domain, string password, uint logonType, uint logonProvider, out IntPtr tokenHandle);
        [DllImport("Advapi32.dll", EntryPoint = "LookupAccountNameW", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Unicode, SetLastError = true, ExactSpelling = true)]
        private static extern unsafe bool LookupAccountName(string systemName, string accountName, void* psid, ref uint sidSize, StringBuilder domainName, ref uint domainLength, out AccountType accountType);
        [DllImport("Advapi32.dll", EntryPoint = "LookupAccountSidW", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Unicode, SetLastError = true, ExactSpelling = true)]
        private static extern bool LookupAccountSid(string systemName, IntPtr psid, StringBuilder accountName, ref uint nameLength, StringBuilder domainName, ref uint domainLength, out AccountType accountType);
        [DllImport("Advapi32.dll", EntryPoint = "LookupAccountSidW", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Unicode, SetLastError = true, ExactSpelling = true)]
        private static extern bool LookupAccountSid(string systemName, byte[] psid, StringBuilder accountName, ref uint nameLength, StringBuilder domainName, ref uint domainLength, out AccountType accountType);
        [DllImport("advapi32.dll", SetLastError = true)]
        public static extern uint LsaAddAccountRights(IntPtr PolicyHandle, byte[] AccountSid, LSA_UNICODE_STRING[] UserRights, uint CountOfRights);
        [DllImport("advapi32.dll")]
        public static extern int LsaClose(IntPtr ObjectHandle);
        [DllImport("advapi32.dll", SetLastError = true)]
        public static extern uint LsaEnumerateAccountRights(IntPtr PolicyHandle, byte[] AccountSid, out IntPtr UserRights, out uint CountOfRights);
        [DllImport("advapi32.dll", SetLastError = true)]
        public static extern uint LsaFreeMemory(IntPtr pBuffer);
        [DllImport("advapi32.dll", SetLastError = true)]
        public static extern uint LsaOpenPolicy(ref LSA_UNICODE_STRING SystemName, ref LSA_OBJECT_ATTRIBUTES ObjectAttributes, uint DesiredAccess, out IntPtr PolicyHandle);
        [DllImport("advapi32.dll", SetLastError = true)]
        public static extern uint LsaRemoveAccountRights(IntPtr PolicyHandle, byte[] AccountSid, byte AllRights, LSA_UNICODE_STRING[] UserRights, uint CountOfRights);
        [DllImport("user32.dll")]
        internal static extern bool MessageBeep(uint uType);
        [DllImport("kernel32", CharSet = CharSet.Auto, SetLastError = true)]
        internal static extern bool MoveFile(string src, string dst);
        [DllImport("kernel32", CharSet = CharSet.Auto, SetLastError = true)]
        internal static extern bool MoveFileEx(string src, string dst, int dwFlags);
        [DllImport("user32")]
        internal static extern bool MoveWindow(HandleRef hWnd, int X, int Y, int Width, int Height, bool repaint);
        internal static byte[] NameToSid(string accountName)
        {
            string str;
            AccountType type;
            return NameToSid(accountName, out str, out type);
        }

        internal static unsafe byte[] NameToSid(string accountName, out string domainName, out AccountType accountType)
        {
            uint sidSize = 0x200;
            byte[] sourceArray = new byte[sidSize];
            uint domainLength = 0x200;
            StringBuilder builder = new StringBuilder((int)domainLength);
            fixed (byte* numRef = sourceArray)
            {
                if (!LookupAccountName(null, accountName, (void*)numRef, ref sidSize, builder, ref domainLength, out accountType))
                {
                    throw new Win32Exception(Marshal.GetLastWin32Error());
                }
                sidSize = GetLengthSid((void*)numRef);
            }
            domainName = builder.ToString();
            byte[] destinationArray = new byte[sidSize];
            Array.Copy(sourceArray, destinationArray, (long)sidSize);
            return destinationArray;
        }

        [DllImport("ncrypt.dll", CharSet = CharSet.Unicode)]
        internal static extern int NCryptCreatePersistedKey(SafeNCryptProviderHandle hProvider, out SafeNCryptKeyHandle phKey, string pszAlgId, string pszKeyName, int dwLegacyKeySpec, CngKeyCreationOptions dwFlags);
        [DllImport("ncrypt.dll")]
        internal static extern int NCryptFinalizeKey(SafeNCryptKeyHandle hKey, int dwFlags);
        [DllImport("ncrypt.dll", CharSet = CharSet.Unicode)]
        internal static extern int NCryptImportKey(SafeNCryptProviderHandle hProvider, IntPtr hImportKey, string pszBlobType, IntPtr pParameterList, out SafeNCryptKeyHandle phKey, [MarshalAs(UnmanagedType.LPArray)] byte[] pbData, int cbData, int dwFlags);
        [DllImport("ncrypt.dll")]
        internal static extern int NCryptOpenStorageProvider(out SafeNCryptProviderHandle phProvider, [MarshalAs(UnmanagedType.LPWStr)] string pszProviderName, int dwFlags);
        [DllImport("ncrypt.dll", CharSet = CharSet.Unicode)]
        internal static extern int NCryptSetProperty(SafeNCryptHandle hObject, string pszProperty, [MarshalAs(UnmanagedType.LPArray)] byte[] pbInput, int cbInput, CngPropertyOptions dwFlags);
        [DllImport("ncrypt.dll")]
        internal static extern int NCryptSignHash(SafeNCryptKeyHandle hKey, [In] ref BCRYPT_PKCS1_PADDING_INFO pPaddingInfo, [In, MarshalAs(UnmanagedType.LPArray)] byte[] pbHashValue, int cbHashValue, [Out, MarshalAs(UnmanagedType.LPArray)] byte[] pbSignature, int cbSignature, out int pcbResult, int dwFlags);
        [DllImport("ncrypt.dll")]
        internal static extern int NCryptVerifySignature(SafeNCryptKeyHandle hKey, [In] ref BCRYPT_PKCS1_PADDING_INFO pPaddingInfo, [In, MarshalAs(UnmanagedType.LPArray)] byte[] pbHashValue, int cbHashValue, [In, MarshalAs(UnmanagedType.LPArray)] byte[] pbSignature, int cbSignature, int dwFlags);
        [DllImport("Netapi32.dll")]
        public static extern int NetApiBufferFree(IntPtr bufferPtr);
        [DllImport("Netapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
        private static extern int NetGetJoinInformation(string server, out IntPtr domain, out NetJoinStatus status);
        public static void NetGetJoinInformation(string server, out string domain, out NetJoinStatus joinStatus)
        {
            IntPtr zero = IntPtr.Zero;
            joinStatus = NetJoinStatus.NetSetupUnknownStatus;
            int error = NetGetJoinInformation(server, out zero, out joinStatus);
            if (zero != IntPtr.Zero)
            {
                domain = Marshal.PtrToStringAuto(zero);
                int num2 = NetApiBufferFree(zero);
                if ((num2 != 0) && (error == 0))
                {
                    throw new Win32Exception(num2);
                }
            }
            else
            {
                domain = string.Empty;
            }
            if (error != 0)
            {
                throw new Win32Exception(error);
            }
        }

        [DllImport("kernel32.dll")]
        internal static extern IntPtr OpenProcess(uint dwDesiredAccess, bool bInheritHandle, uint dwProcessId);
        [DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
        public static extern ServiceHandle OpenSCManager(string machineName, string db, ServiceControlAccessRights desiredAccess);
        [DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
        public static extern ServiceHandle OpenService(ServiceHandle serviceControlManagerHandle, string serviceName, ServiceAccessRights desiredAccess);
        [DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
        internal static extern void OutputDebugString(string s);
        [DllImport("shlwapi.dll", CharSet = CharSet.Unicode)]
        internal static extern bool PathIsDirectoryEmpty(string path);
        [DllImport("kernel32", CharSet = CharSet.Auto, SetLastError = true)]
        internal static extern bool PeekConsoleInput(IntPtr hConsoleInput, IntPtr buffer, uint numInputRecords, out uint numEventsRead);
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        internal static extern bool PeekMessage(out MSG msg, IntPtr hwnd, uint filterMin, uint filterMax, bool removeMsg);
        [DllImport("user32", CharSet = CharSet.Auto, SetLastError = true)]
        internal static extern int PostMessage(HandleRef hWnd, int msg, IntPtr wParam, IntPtr lParam);
        [DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
        public static extern int QueryServiceConfigW(ServiceHandle serviceHandle, IntPtr serviceConfigHandle, int bufferSize, out int bytesNeeded);
        [DllImport("user32", CharSet = CharSet.Unicode, SetLastError = true)]
        internal static extern short RegisterClass(WNDCLASS wc);
        [DllImport("user32", CharSet = CharSet.Unicode)]
        internal static extern int RegisterWindowMessage(string msg);
        [DllImport("user32.dll")]
        internal static extern bool ReleaseCapture();
        [DllImport("user32", CharSet = CharSet.Auto, ExactSpelling = true)]
        public static extern int ReleaseDC(IntPtr hWnd, IntPtr hDC);
        [DllImport("user32", CharSet = CharSet.Auto, ExactSpelling = true)]
        internal static extern int ReleaseDC(HandleRef hwnd, HandleRef hdc);
        [DllImport("user32", CharSet = CharSet.Auto)]
        internal static extern bool ScreenToClient(HandleRef hWnd, ref POINT pt);
        [DllImport("gdi32", CharSet = CharSet.Auto, SetLastError = true, ExactSpelling = true)]
        internal static extern IntPtr SelectObject(IntPtr hdc, IntPtr hObject);
        [DllImport("User32.dll", CharSet = CharSet.Unicode)]
        internal static extern IntPtr SendMessage(IntPtr hWnd, int msg, int wParam, int lParam);
        [DllImport("user32", CharSet = CharSet.Unicode)]
        internal static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam);
        [DllImport("User32.dll", CharSet = CharSet.Unicode)]
        internal static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wParam, ref LVITEM lParam);
        [DllImport("user32.dll", CharSet = CharSet.Unicode)]
        internal static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wParam, ref TV_HITTESTINFO lParam);
        [DllImport("user32.dll", CharSet = CharSet.Unicode)]
        internal static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wParam, ref TVITEM lParam);
        [DllImport("User32.dll", CharSet = CharSet.Unicode)]
        internal static extern IntPtr SendMessage(HandleRef hWnd, int msg, IntPtr wParam, ref HDITEM lParam);
        [DllImport("user32", CharSet = CharSet.Unicode)]
        internal static extern IntPtr SendMessage(HandleRef hWnd, int msg, IntPtr wParam, ref LVHITTESTINFO lParam);
        [DllImport("user32.dll", CharSet = CharSet.Unicode)]
        internal static extern IntPtr SendMessage(HandleRef hWnd, int msg, IntPtr wParam, IntPtr lParam);
        [DllImport("user32", CharSet = CharSet.Unicode)]
        internal static extern IntPtr SendMessage(HandleRef hWnd, int msg, IntPtr wparam, StringBuilder lparam);
        [DllImport("user32", CharSet = CharSet.Unicode)]
        internal static extern IntPtr SendMessage(HandleRef hWnd, int msg, IntPtr wParam, ref LVITEM_NOTEXT lParam);
        [DllImport("user32", CharSet = CharSet.Unicode)]
        internal static extern IntPtr SendMessage(HandleRef hWnd, int msg, IntPtr wparam, string lparam);
        [DllImport("user32", CharSet = CharSet.Unicode)]
        internal static extern IntPtr SendMessage(HandleRef hWnd, int msg, IntPtr wParam, ref RECT rect);
        internal static IntPtr SendMessage(object control, IntPtr handle, int msg, int wParam, int lParam)
        {
            return SendMessage(new HandleRef(control, handle), msg, (IntPtr)wParam, (IntPtr)lParam);
        }

        [DllImport("user32.dll", CharSet = CharSet.Unicode)]
        internal static extern IntPtr SendMessageW(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam);
        [DllImport("user32", CharSet = CharSet.Auto, SetLastError = true)]
        internal static extern IntPtr SetActiveWindow(IntPtr hwnd);
        [DllImport("user32", CharSet = CharSet.Auto)]
        internal static extern IntPtr SetCursor(HandleRef hcursor);
        internal static void SetFileCompression(SafeHandle handle, short compressionFormat)
        {
            uint num;
            if (!DeviceIoControl(handle, 0x9c040, ref compressionFormat, 2, IntPtr.Zero, 0, out num, IntPtr.Zero))
            {
                throw new Win32Exception();
            }
        }

        [DllImport("user32", CharSet = CharSet.Auto, ExactSpelling = true)]
        internal static extern IntPtr SetFocus(IntPtr hWnd);
        [DllImport("user32", CharSet = CharSet.Auto, ExactSpelling = true)]
        internal static extern IntPtr SetFocus(HandleRef hWnd);
        [DllImport("user32", CharSet = CharSet.Auto, SetLastError = true)]
        internal static extern int SetForegroundWindow(IntPtr hwnd);
        [DllImport("advapi32.dll", CharSet = CharSet.Unicode)]
        public static extern uint SetNamedSecurityInfo(string objectName, ResourceType objectType, SecurityInfos securityInfo, byte[] sidOwner, byte[] sidGroup, byte[] dacl, byte[] sacl);
        [DllImport("user32.dll")]
        internal static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent);
        [DllImport("user32")]
        internal static extern IntPtr SetTimer(HandleRef hWnd, int nIDEvent, int uElapse, IntPtr lpTimerFunc);
        [DllImport("user32", CharSet = CharSet.Auto)]
        internal static extern IntPtr SetWindowLong(IntPtr hWnd, int nIndex, IntPtr dwNewLong);
        [DllImport("user32", CharSet = CharSet.Auto)]
        internal static extern IntPtr SetWindowLong(HandleRef hWnd, int nIndex, HandleRef dwNewLong);
        [DllImport("user32.dll")]
        internal static extern bool SetWindowPos(IntPtr hWnd, int hWndInsertAfter, int X, int Y, int cx, int cy, int uFlags);
        [DllImport("user32", CharSet = CharSet.Auto, ExactSpelling = true)]
        internal static extern bool SetWindowPos(HandleRef hWnd, HandleRef hWndInsertAfter, int x, int y, int cx, int cy, int flags);
        [DllImport("user32", CharSet = CharSet.Unicode)]
        internal static extern bool SetWindowText(HandleRef hWnd, string text);
        [DllImport("uxtheme.dll", CharSet = CharSet.Unicode)]
        public static extern int SetWindowTheme(IntPtr hWnd, string subAppName, string subIdList);
        [DllImport("shlwapi.dll")]
        internal static extern int SHAutoComplete(IntPtr hwndEdit, int dwFlags);
        [DllImport("shell32", CharSet = CharSet.Auto)]
        internal static extern IntPtr SHBrowseForFolder([In, Out] ref BROWSEINFO lpbi);
        [DllImport("shell32.dll", CharSet = CharSet.Unicode)]
        internal static extern IntPtr ShellExecute(IntPtr hParentWnd, [MarshalAs(UnmanagedType.LPWStr)] string operation, [MarshalAs(UnmanagedType.LPWStr)] string file, [MarshalAs(UnmanagedType.LPWStr)] string parameters, [MarshalAs(UnmanagedType.LPWStr)] string directory, int showCmd);
        internal static int SHFileOperationDelete(string path)
        {
            SHFILEOPSTRUCT fileOp = new SHFILEOPSTRUCT
            {
                wFunc = 3,
                fFlags = 0x454,
                pFrom = path + NullString
            };
            return SHFileOperationW(ref fileOp);
        }

        [DllImport("shell32", CharSet = CharSet.Unicode)]
        private static extern int SHFileOperationW([In] ref SHFILEOPSTRUCT fileOp);
        [DllImport("shell32.dll", CharSet = CharSet.Unicode)]
        internal static extern IntPtr SHGetFileInfoW(string pszPath, int dwFileAttributes, ref ShFileInfoW psfi, int cbSizeFileInfo, int uFlags);
        [DllImport("shell32")]
        internal static extern int SHGetMalloc([MarshalAs(UnmanagedType.Interface)] out IMalloc ppMalloc);
        [DllImport("shell32", CharSet = CharSet.Auto)]
        internal static extern bool SHGetPathFromIDList(IntPtr pidl, IntPtr pszPath);
        [DllImport("shell32")]
        internal static extern int SHGetSpecialFolderLocation(IntPtr hwnd, int csidl, ref IntPtr ppidl);
        [DllImport("user32.dll")]
        public static extern bool ShowScrollBar(IntPtr hWnd, int wBar, bool bShow);
        [DllImport("user32.dll")]
        internal static extern bool ShowWindow(IntPtr hWnd, int flags);
        [DllImport("user32", CharSet = CharSet.Auto, ExactSpelling = true)]
        internal static extern bool ShowWindow(HandleRef hWnd, int nCmdShow);
        public static string SidToAccount(byte[] sid)
        {
            AccountType type;
            uint nameLength = 0x200;
            StringBuilder accountName = new StringBuilder((int)nameLength);
            uint domainLength = 0x200;
            StringBuilder domainName = new StringBuilder((int)domainLength);
            if (!LookupAccountSid(null, sid, accountName, ref nameLength, domainName, ref domainLength, out type))
            {
                throw new Win32Exception(Marshal.GetLastWin32Error());
            }
            return (domainName.ToString() + @"\" + accountName.ToString());
        }

        public static string SidToName(IntPtr sid, out string domainName, out AccountType accountType)
        {
            uint nameLength = 0x200;
            StringBuilder accountName = new StringBuilder((int)nameLength);
            uint domainLength = 0x200;
            StringBuilder builder2 = new StringBuilder((int)domainLength);
            if (!LookupAccountSid(null, sid, accountName, ref nameLength, builder2, ref domainLength, out accountType))
            {
                throw new Win32Exception(Marshal.GetLastWin32Error());
            }
            domainName = builder2.ToString();
            return accountName.ToString();
        }

        public static string SidToName(byte[] sid, out string domainName, out AccountType accountType)
        {
            uint nameLength = 0x200;
            StringBuilder accountName = new StringBuilder((int)nameLength);
            uint domainLength = 0x200;
            StringBuilder builder2 = new StringBuilder((int)domainLength);
            if (!LookupAccountSid(null, sid, accountName, ref nameLength, builder2, ref domainLength, out accountType))
            {
                throw new Win32Exception(Marshal.GetLastWin32Error());
            }
            domainName = builder2.ToString();
            return accountName.ToString();
        }

        [DllImport("OLE32.DLL", CharSet = CharSet.Unicode, PreserveSig = false)]
        public static extern int StgCreateDocfile([MarshalAs(UnmanagedType.LPWStr)] string pwcsName, uint grfMode, uint reserved, out IStorage ppstgOpen);
        [DllImport("OLE32.DLL", CharSet = CharSet.Unicode, PreserveSig = false)]
        public static extern IStorage StgCreateDocfileOnILockBytes(ILockBytes plkbyt, uint grfMode, uint reserved);
        [DllImport("Shlwapi.dll", CharSet = CharSet.Unicode)]
        public static extern long StrFormatByteSize(long qdw, StringBuilder pszBuf, int cchBuf);
        [DllImport("ole32.dll", CharSet = CharSet.Unicode)]
        private static extern int StringFromGUID2(IntPtr pguid, StringBuilder lpsz, int cchMax);
        [DllImport("user32")]
        internal static extern bool SystemParametersInfo(int nAction, int nParam, ref int value, int ignore);
        [DllImport("kernel32.dll")]
        internal static extern bool TerminateJobObject(SafeHandle hJob, uint uExitCode);
        [return: MarshalAs(UnmanagedType.Bool)]
        [DllImport("advapi32.dll")]
        public static extern bool UnlockServiceDatabase(IntPtr handle);
        [DllImport("user32", CharSet = CharSet.Unicode, SetLastError = true)]
        internal static extern bool UnregisterClass(string lpClassName, IntPtr hInstance);
        [DllImport("user32", ExactSpelling = true)]
        internal static extern bool UpdateWindow(HandleRef hWnd);
        internal static IntPtr WindowFromPoint(int x, int y)
        {
            POINTSTRUCT pt = new POINTSTRUCT(x, y);
            return _WindowFromPoint(pt);
        }

        [DllImport("mpr.dll", CharSet = CharSet.Unicode)]
        internal static extern int WNetAddConnection2(NETRESOURCE resource, string lpPassword, string lpUserName, int dwFlags);
        internal static bool WriteConsole(IntPtr hConsoleOutput, char[] chars)
        {
            return WriteConsole(hConsoleOutput, chars, chars.Length);
        }

        internal static bool WriteConsole(IntPtr hConsoleOutput, char[] chars, int charsToWrite)
        {
            uint num;
            return WriteConsole(hConsoleOutput, chars, charsToWrite, out num);
        }

        internal static unsafe bool WriteConsole(IntPtr hConsoleOutput, char[] chars, int charsToWrite, out uint numCharsWritten)
        {
            numCharsWritten = 0;
            if (chars == null)
            {
                return WriteConsole(hConsoleOutput, null, 0, out numCharsWritten, IntPtr.Zero);
            }
            charsToWrite = Math.Min(charsToWrite, chars.Length);
            bool flag = true;
            fixed (char* chRef = chars)
            {
                uint num = (uint)charsToWrite;
                while (flag && (numCharsWritten < num))
                {
                    uint numCharsToWrite = Math.Min(Math.Min(num, 0x2000), num - numCharsWritten);
                    uint num3 = 0;
                    flag = WriteConsole(hConsoleOutput, chRef + numCharsWritten, numCharsToWrite, out num3, IntPtr.Zero);
                    numCharsWritten += num3;
                }
            }
            return flag;
        }

        [DllImport("kernel32", CharSet = CharSet.Auto, SetLastError = true)]
        internal static extern unsafe bool WriteConsole(IntPtr hConsoleOutput, char* text, uint numCharsToWrite, out uint numCharsWritten, IntPtr mustBeZero);
        internal static bool WriteFile(IntPtr handle, byte[] bytes)
        {
            return WriteFile(handle, bytes, bytes.Length);
        }

        internal static bool WriteFile(IntPtr handle, char[] chars)
        {
            return WriteFile(handle, chars, chars.Length);
        }

        internal static bool WriteFile(IntPtr handle, byte[] bytes, int numBytesToWrite)
        {
            uint num;
            return WriteFile(handle, bytes, numBytesToWrite, out num);
        }

        internal static bool WriteFile(IntPtr handle, char[] chars, int numCharsToWrite)
        {
            uint num;
            return WriteFile(handle, chars, numCharsToWrite, out num);
        }

        internal static unsafe bool WriteFile(IntPtr handle, byte[] bytes, int numBytesToWrite, out uint numBytesWritten)
        {
            if ((bytes == null) || (numBytesToWrite <= 0))
            {
                numBytesWritten = 0;
                return true;
            }
            numBytesToWrite = Math.Min(numBytesToWrite, bytes.Length);
            fixed (byte* numRef = bytes)
            {
                numBytesWritten = 0;
                return WriteFile(handle, numRef, numBytesToWrite, out numBytesWritten, IntPtr.Zero);
            }
        }

        internal static unsafe bool WriteFile(IntPtr handle, char[] chars, int numCharsToWrite, out uint numCharsWritten)
        {
            if ((chars == null) || (numCharsToWrite <= 0))
            {
                numCharsWritten = 0;
                return true;
            }
            numCharsToWrite = Math.Min(numCharsToWrite, chars.Length);
            fixed (char* chRef = chars)
            {
                byte* bytes = (byte*)chRef;
                uint numBytesWritten = 0;
                bool flag = WriteFile(handle, bytes, numCharsToWrite * 2, out numBytesWritten, IntPtr.Zero);
                numCharsWritten = numBytesWritten / 2;
                return flag;
            }
        }

        [DllImport("kernel32", SetLastError = true)]
        private static extern unsafe bool WriteFile(IntPtr handle, byte* bytes, int numBytesToWrite, out uint numBytesWritten, IntPtr mustBeZero);
        [DllImport("kernel32.dll", SetLastError = true)]
        internal static extern void ZeroMemory(IntPtr address, uint byteCount);

        // Properties
        public static bool IsWow64
        {
            get
            {
                bool flag;
                if (!IsWow64Process(Process.GetCurrentProcess().Handle, out flag))
                {
                    throw new Win32Exception();
                }
                return flag;
            }
        }

        private static string NullString
        {
            get
            {
                char ch = '\0';
                return ch.ToString();
            }
        }

        // Nested Types
        internal enum AccountType
        {
            SidTypeAlias = 4,
            SidTypeComputer = 9,
            SidTypeDeletedAccount = 6,
            SidTypeDomain = 3,
            SidTypeGroup = 2,
            SidTypeInvalid = 7,
            SidTypeUnknown = 8,
            SidTypeUser = 1,
            SidTypeWellKnownGroup = 5
        }

        public enum ACL_INFORMATION_CLASS
        {
            AclRevisionInformation = 1,
            AclSizeInformation = 2
        }

        [StructLayout(LayoutKind.Sequential)]
        public struct ACL_SIZE_INFORMATION
        {
            public uint AceCount;
            public uint AclBytesInUse;
            public uint AclBytesFree;
        }

        private enum AUTHZ_CONTEXT_INFORMATION_CLASS
        {
            AuthzContextInfoAll = 9,
            AuthzContextInfoAuthenticationId = 10,
            AuthzContextInfoExpirationTime = 5,
            AuthzContextInfoGroupsSids = 2,
            AuthzContextInfoIdentifier = 7,
            AuthzContextInfoPrivileges = 4,
            AuthzContextInfoRestrictedSids = 3,
            AuthzContextInfoServerContext = 6,
            AuthzContextInfoSource = 8,
            AuthzContextInfoUserSid = 1
        }

        [StructLayout(LayoutKind.Sequential)]
        internal struct BCRYPT_PKCS1_PADDING_INFO
        {
            [MarshalAs(UnmanagedType.LPWStr)]
            internal string pszAlgId;
        }

        internal delegate int BrowseCallbackProc(IntPtr hwnd, int msg, IntPtr lParam, IntPtr lpData);

        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
        internal struct BROWSEINFO
        {
            internal IntPtr hwndOwner;
            internal IntPtr pidlRoot;
            internal IntPtr pszDisplayName;
            internal string lpszTitle;
            internal uint ulFlags;
            internal NativeMethods.BrowseCallbackProc lpfn;
            internal IntPtr lParam;
            internal int iImage;
        }

        [Flags]
        internal enum BrowseInfos : uint
        {
            BrowseForComputer = 0x1000,
            BrowseForEverything = 0x4000,
            BrowseForPrinter = 0x2000,
            HideNewFolderButton = 0x200,
            NewDialogStyle = 0x40,
            RestrictToDomain = 2,
            RestrictToFilesystem = 1,
            RestrictToSubfolders = 8,
            ShowTextBox = 0x10,
            ValidateSelection = 0x20
        }

        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto, Pack = 4)]
        public struct CHARFORMAT2
        {
            public int cbSize;
            public int dwMask;
            public int dwEffects;
            public int yHeight;
            public int yOffset;
            public int crTextColor;
            public byte bCharSet;
            public byte bPitchAndFamily;
            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 0x20)]
            public string szFaceName;
            public short wWeight;
            public short sSpacing;
            public int crBackColor;
            public int lcid;
            public int dwReserved;
            public short sStyle;
            public short wKerning;
            public byte bUnderlineType;
            public byte bAnimation;
            public byte bRevAuthor;
            public byte bReserved1;
        }

        [StructLayout(LayoutKind.Sequential)]
        internal class COMBOBOXINFO
        {
            [MarshalAs(UnmanagedType.U4)]
            internal int cbSize = Marshal.SizeOf(typeof(NativeMethods.COMBOBOXINFO));
            internal NativeMethods.RECT rcItem = new NativeMethods.RECT();
            internal NativeMethods.RECT rcButton = new NativeMethods.RECT();
            [MarshalAs(UnmanagedType.U4)]
            internal int stateButton;
            internal IntPtr hwndCombo = new IntPtr();
            internal IntPtr hwndItem = new IntPtr();
            internal IntPtr hwndList = new IntPtr();
        }

        public enum COMPUTER_NAME_FORMAT
        {
            ComputerNameNetBIOS,
            ComputerNameDnsHostname,
            ComputerNameDnsDomain,
            ComputerNameDnsFullyQualified,
            ComputerNamePhysicalNetBIOS,
            ComputerNamePhysicalDnsHostname,
            ComputerNamePhysicalDnsDomain,
            ComputerNamePhysicalDnsFullyQualified,
            ComputerNameMax
        }

        [Flags]
        internal enum ConnectFlags : uint
        {
            CONNECT_CMD_SAVECRED = 0x1000,
            CONNECT_COMMANDLINE = 0x800,
            CONNECT_CURRENT_MEDIA = 0x200,
            CONNECT_DEFERRED = 0x400,
            CONNECT_INTERACTIVE = 8,
            CONNECT_LOCALDRIVE = 0x100,
            CONNECT_NEED_DRIVE = 0x20,
            CONNECT_PROMPT = 0x10,
            CONNECT_REDIRECT = 0x80,
            CONNECT_REFCOUNT = 0x40,
            CONNECT_RESERVED = 0xff000000,
            CONNECT_TEMPORARY = 4,
            CONNECT_UPDATE_PROFILE = 1,
            CONNECT_UPDATE_RECENT = 2
        }

        internal enum CreationDisposition : uint
        {
            CreateAlways = 2,
            New = 1,
            OpenAlways = 4,
            OpenExisting = 3,
            TruncateExisting = 5
        }

        [StructLayout(LayoutKind.Sequential)]
        internal struct CREDENTIAL
        {
            public int Flags;
            public int Type;
            [MarshalAs(UnmanagedType.LPWStr)]
            public string TargetName;
            [MarshalAs(UnmanagedType.LPWStr)]
            public string Comment;
            public System.Runtime.InteropServices.ComTypes.FILETIME LastWritten;
            public int CredentialBlobSize;
            public IntPtr CredentialBlob;
            public int Persist;
            public int AttributeCount;
            public IntPtr Attributes;
            [MarshalAs(UnmanagedType.LPWStr)]
            public string TargetAlias;
            [MarshalAs(UnmanagedType.LPWStr)]
            public string UserName;
        }

        [StructLayout(LayoutKind.Sequential)]
        internal struct CREDUI_INFO
        {
            public int cbSize;
            public IntPtr hwndParent;
            [MarshalAs(UnmanagedType.LPWStr)]
            public string pszMessageText;
            [MarshalAs(UnmanagedType.LPWStr)]
            public string pszCaptionText;
            public IntPtr hbmBanner;
        }

        internal class DlgStyle
        {
            // Fields
            internal const int Ds3dLook = 4;
            internal const int DsControl = 0x400;
            internal const int DsSetFont = 0x40;
            internal const int SsNotify = 0x100;
            internal const int WsChild = 0x40000000;
            internal const int WsClipSiblings = 0x4000000;
            internal const int WsGroup = 0x20000;
            internal const int WsVisible = 0x10000000;
        }

        [StructLayout(LayoutKind.Sequential)]
        internal class DlgTemplatePlaceholder
        {
            internal int style = 0x44000504;
            internal int extendedStyle = 0x10000;
            internal short numItems = 1;
            internal short x;
            internal short y;
            internal short cx;
            internal short cy;
            internal short reservedMenu;
            internal short reservedClass;
            internal short reservedTitle;
            internal int itemStyle = 0x40000000;
            internal int itemExtendedStyle = 4;
            internal short itemX;
            internal short itemY;
            internal short itemCx;
            internal short itemCy;
            internal short itemId;
            internal ushort itemClassHdr = 0xffff;
            internal short itemClass = 130;
            internal short itemText;
            internal short itemData;
        }

        [StructLayout(LayoutKind.Sequential)]
        public class DRAWTEXTPARAMS
        {
            private int cbSize = Marshal.SizeOf(typeof(NativeMethods.DRAWTEXTPARAMS));
            public int iTabLength;
            public int iLeftMargin;
            public int iRightMargin;
            public int uiLengthDrawn;
        }

        public enum DS_NAME_ERROR
        {
            DS_NAME_NO_ERROR,
            DS_NAME_ERROR_RESOLVING,
            DS_NAME_ERROR_NOT_FOUND,
            DS_NAME_ERROR_NOT_UNIQUE,
            DS_NAME_ERROR_NO_MAPPING,
            DS_NAME_ERROR_DOMAIN_ONLY,
            DS_NAME_ERROR_NO_SYNTACTICAL_MAPPING,
            DS_NAME_ERROR_TRUST_REFERRAL
        }

        [Flags]
        public enum DS_NAME_FLAGS
        {
            DS_NAME_FLAG_EVAL_AT_DC = 2,
            DS_NAME_FLAG_GCVERIFY = 4,
            DS_NAME_FLAG_SYNTACTICAL_ONLY = 1,
            DS_NAME_FLAG_TRUST_REFERRAL = 8,
            DS_NAME_NO_FLAGS = 0
        }

        public enum DS_NAME_FORMAT : uint
        {
            DS_CANONICAL_NAME = 7,
            DS_CANONICAL_NAME_EX = 9,
            DS_DISPLAY_NAME = 3,
            DS_DNS_DOMAIN_NAME = 12,
            DS_FQDN_1779_NAME = 1,
            DS_NT4_ACCOUNT_NAME = 2,
            DS_SERVICE_PRINCIPAL_NAME = 10,
            DS_SID_OR_SID_HISTORY_NAME = 11,
            DS_UNIQUE_ID_NAME = 6,
            DS_UNKNOWN_NAME = 0,
            DS_USER_PRINCIPAL_NAME = 8
        }

        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
        internal struct DS_NAME_RESULT
        {
            internal uint cItems;
            internal IntPtr rItems;
        }

        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
        public struct DS_NAME_RESULT_ITEM
        {
            public NativeMethods.DS_NAME_ERROR status;
            public string pDomain;
            public string pName;
        }

        internal enum DS_SITE_NAME_ERROR
        {
            DS_SITE_NAME_ERROR_NOT_ENOUGH_MEMORY = 8,
            DS_SITE_NAME_ERROR_NOT_SITENAME = 0x77f,
            DS_SITE_NAME_NO_ERROR = 0
        }

        internal delegate int EnumWindowsProc(IntPtr hwnd, IntPtr lParam);

        internal class ExStyle
        {
            // Fields
            internal const int WsExControlParent = 0x10000;
            internal const int WsExNoParentNotify = 4;
        }

        [Flags]
        internal enum FileAccess : uint
        {
            GenericAll = 0x10000000,
            GenericExecute = 0x20000000,
            GenericRead = 0x80000000,
            GenericWrite = 0x40000000
        }

        [Flags]
        internal enum FileAttributes : uint
        {
            Archive = 0x20,
            BackupSemantics = 0x2000000,
            Compressed = 0x800,
            DeleteOnClose = 0x4000000,
            Device = 0x40,
            Directory = 0x10,
            Encrypted = 0x4000,
            FirstPipeInstance = 0x80000,
            Hidden = 2,
            NoBuffering = 0x20000000,
            Normal = 0x80,
            NotContentIndexed = 0x2000,
            Offline = 0x1000,
            OpenNoRecall = 0x100000,
            OpenReparsePoint = 0x200000,
            Overlapped = 0x40000000,
            PosixSemantics = 0x1000000,
            RandomAccess = 0x10000000,
            Readonly = 1,
            ReparsePoint = 0x400,
            SequentialScan = 0x8000000,
            SparseFile = 0x200,
            System = 4,
            Temporary = 0x100,
            Write_Through = 0x80000000
        }

        [Flags]
        internal enum FileShare : uint
        {
            Delete = 4,
            None = 0,
            Read = 1,
            Write = 2
        }

        [StructLayout(LayoutKind.Sequential)]
        internal struct FLASHWINFO
        {
            internal uint cbSize;
            internal IntPtr hwnd;
            internal uint dwFlags;
            internal uint uCount;
            internal uint dwTimeout;
        }

        internal enum GetAncestorFlags
        {
            Parent = 1,
            Root = 2,
            RootOwner = 3
        }

        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
        internal struct HDITEM
        {
            internal int mask;
            internal int cxy;
            internal IntPtr pszText;
            internal IntPtr hbm;
            internal int cchTextMax;
            internal int fmt;
            internal IntPtr lParam;
            internal int iImage;
            internal int iOrder;
            internal int type;
            internal IntPtr pvFilter;
        }

        [ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("0000000A-0000-0000-C000-000000000046")]
        public interface ILockBytes
        {
            void ReadAt([In, MarshalAs(UnmanagedType.U8)] long ulOffset, [Out, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] byte[] pv, [In, MarshalAs(UnmanagedType.U4)] int cb, [Out, MarshalAs(UnmanagedType.LPArray)] int[] pcbRead);
            void WriteAt([In, MarshalAs(UnmanagedType.U8)] long ulOffset, IntPtr pv, [In, MarshalAs(UnmanagedType.U4)] int cb, [Out, MarshalAs(UnmanagedType.LPArray)] int[] pcbWritten);
            void Flush();
            void SetSize([In, MarshalAs(UnmanagedType.U8)] long cb);
            void LockRegion([In, MarshalAs(UnmanagedType.U8)] long libOffset, [In, MarshalAs(UnmanagedType.U8)] long cb, [In, MarshalAs(UnmanagedType.U4)] int dwLockType);
            void UnlockRegion([In, MarshalAs(UnmanagedType.U8)] long libOffset, [In, MarshalAs(UnmanagedType.U8)] long cb, [In, MarshalAs(UnmanagedType.U4)] int dwLockType);
            void Stat(out System.Runtime.InteropServices.ComTypes.STATSTG pstatstg, [In, MarshalAs(UnmanagedType.U4)] int grfStatFlag);
        }

        [StructLayout(LayoutKind.Sequential)]
        internal struct IMAGEINFO
        {
            internal IntPtr hbmImage;
            internal IntPtr hbmMask;
            internal int Unused1;
            internal int Unused2;
            internal NativeMethods.RECT rcImage;
        }

        [ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), SuppressUnmanagedCodeSecurity, Guid("00000002-0000-0000-c000-000000000046")]
        internal interface IMalloc
        {
            [PreserveSig]
            IntPtr Alloc(int cb);
            [PreserveSig]
            IntPtr Realloc(IntPtr pv, int cb);
            [PreserveSig]
            void Free(IntPtr pv);
            [PreserveSig]
            int GetSize(IntPtr pv);
            [PreserveSig]
            int DidAlloc(IntPtr pv);
            [PreserveSig]
            void HeapMinimize();
        }

        [ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("00000016-0000-0000-C000-000000000046")]
        internal interface IOleMessageFilter
        {
            [PreserveSig]
            int HandleInComingCall(int dwCallType, IntPtr hTaskCaller, int dwTickCount, IntPtr lpInterfaceInfo);
            [PreserveSig]
            int RetryRejectedCall(IntPtr hTaskCallee, int dwTickCount, int dwRejectType);
            [PreserveSig]
            int MessagePending(IntPtr hTaskCallee, int dwTickCount, int dwPendingType);
        }

        [ComImport, Guid("0000000B-0000-0000-C000-000000000046"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
        public interface IStorage
        {
            [return: MarshalAs(UnmanagedType.Interface)]
            System.Runtime.InteropServices.ComTypes.IStream CreateStream([In, MarshalAs(UnmanagedType.BStr)] string pwcsName, [In, MarshalAs(UnmanagedType.U4)] int grfMode, [In, MarshalAs(UnmanagedType.U4)] int reserved1, [In, MarshalAs(UnmanagedType.U4)] int reserved2);
            [return: MarshalAs(UnmanagedType.Interface)]
            System.Runtime.InteropServices.ComTypes.IStream OpenStream([In, MarshalAs(UnmanagedType.BStr)] string pwcsName, IntPtr reserved1, [In, MarshalAs(UnmanagedType.U4)] int grfMode, [In, MarshalAs(UnmanagedType.U4)] int reserved2);
            [return: MarshalAs(UnmanagedType.Interface)]
            NativeMethods.IStorage CreateStorage([In, MarshalAs(UnmanagedType.BStr)] string pwcsName, [In, MarshalAs(UnmanagedType.U4)] int grfMode, [In, MarshalAs(UnmanagedType.U4)] int reserved1, [In, MarshalAs(UnmanagedType.U4)] int reserved2);
            [return: MarshalAs(UnmanagedType.Interface)]
            NativeMethods.IStorage OpenStorage([In, MarshalAs(UnmanagedType.BStr)] string pwcsName, IntPtr pstgPriority, [In, MarshalAs(UnmanagedType.U4)] int grfMode, IntPtr snbExclude, [In, MarshalAs(UnmanagedType.U4)] int reserved);
            void CopyTo(int ciidExclude, [In, MarshalAs(UnmanagedType.LPArray)] Guid[] pIIDExclude, IntPtr snbExclude, [In, MarshalAs(UnmanagedType.Interface)] NativeMethods.IStorage stgDest);
            void MoveElementTo([In, MarshalAs(UnmanagedType.BStr)] string pwcsName, [In, MarshalAs(UnmanagedType.Interface)] NativeMethods.IStorage stgDest, [In, MarshalAs(UnmanagedType.BStr)] string pwcsNewName, [In, MarshalAs(UnmanagedType.U4)] int grfFlags);
            void Commit(int grfCommitFlags);
            void Revert();
            void EnumElements([In, MarshalAs(UnmanagedType.U4)] int reserved1, IntPtr reserved2, [In, MarshalAs(UnmanagedType.U4)] int reserved3, [MarshalAs(UnmanagedType.Interface)] out object ppVal);
            void DestroyElement([In, MarshalAs(UnmanagedType.BStr)] string pwcsName);
            void RenameElement([In, MarshalAs(UnmanagedType.BStr)] string pwcsOldName, [In, MarshalAs(UnmanagedType.BStr)] string pwcsNewName);
            void SetElementTimes([In, MarshalAs(UnmanagedType.BStr)] string pwcsName, [In] System.Runtime.InteropServices.ComTypes.FILETIME pctime, [In] System.Runtime.InteropServices.ComTypes.FILETIME patime, [In] System.Runtime.InteropServices.ComTypes.FILETIME pmtime);
            void SetClass([In] ref Guid clsid);
            void SetStateBits(int grfStateBits, int grfMask);
            void Stat(out System.Runtime.InteropServices.ComTypes.STATSTG pStatStg, int grfStatFlag);
        }

        [StructLayout(LayoutKind.Sequential)]
        public struct LSA_OBJECT_ATTRIBUTES
        {
            public uint Length;
            public IntPtr RootDirectory;
            public NativeMethods.LSA_UNICODE_STRING ObjectName;
            public uint Attributes;
            public IntPtr SecurityDescriptor;
            public IntPtr SecurityQualityOfService;
        }

        [StructLayout(LayoutKind.Sequential)]
        public struct LSA_UNICODE_STRING
        {
            public ushort Length;
            public ushort MaximumLength;
            public IntPtr Buffer;
        }

        [StructLayout(LayoutKind.Sequential)]
        internal struct LUID
        {
            internal uint LowPart;
            internal uint HighPart;
        }

        [StructLayout(LayoutKind.Sequential)]
        internal struct LVCOLUMN
        {
            internal int mask;
            internal int fmt;
            internal int cx;
            internal IntPtr pszText;
            internal int cchTextMax;
            internal int iSubItem;
            internal int iImage;
            internal int iOrder;
        }

        [StructLayout(LayoutKind.Sequential)]
        public struct LVHITTESTINFO
        {
            public int pt_x;
            public int pt_y;
            public int flags;
            public int iItem;
            public int iSubItem;
        }

        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
        internal struct LVITEM
        {
            public int mask;
            public int iItem;
            public int iSubItem;
            public int state;
            public int stateMask;
            public string pszText;
            public int cchTextMax;
            public int iImage;
            public IntPtr lParam;
            public int iIndent;
            public int iGroupId;
            public int cColumns;
            public IntPtr puColumns;
        }

        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
        public struct LVITEM_NOTEXT
        {
            public int mask;
            public int iItem;
            public int iSubItem;
            public int state;
            public int stateMask;
            public IntPtr pszText;
            public int cchTextMax;
            public int iImage;
            public IntPtr lParam;
            public int iIndent;
        }

        [Flags]
        internal enum MoveFileOption
        {
            MOVEFILE_COPY_ALLOWED = 2,
            MOVEFILE_CREATE_HARDLINK = 0x10,
            MOVEFILE_DELAY_UNTIL_REBOOT = 4,
            MOVEFILE_FAIL_IF_NOT_TRACKABLE = 0x20,
            MOVEFILE_REPLACE_EXISTING = 1,
            MOVEFILE_WRITE_THROUGH = 8
        }

        [Serializable, StructLayout(LayoutKind.Sequential)]
        internal struct MSG
        {
            internal IntPtr hwnd;
            internal int message;
            internal IntPtr wParam;
            internal IntPtr lParam;
            internal int time;
            internal int pt_x;
            internal int pt_y;
        }

        public enum NetJoinStatus
        {
            NetSetupUnknownStatus,
            NetSetupUnjoined,
            NetSetupWorkgroupName,
            NetSetupDomainName
        }

        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
        internal class NETRESOURCE
        {
            [MarshalAs(UnmanagedType.U4)]
            internal NativeMethods.ResourceScope dwScope;
            [MarshalAs(UnmanagedType.U4)]
            internal NativeMethods.ResourceType dwType;
            [MarshalAs(UnmanagedType.U4)]
            internal NativeMethods.ResourceDisplayType dwDisplayType;
            [MarshalAs(UnmanagedType.U4)]
            internal NativeMethods.ResourceUsageType dwUsage;
            [MarshalAs(UnmanagedType.LPWStr)]
            internal string LocalName;
            [MarshalAs(UnmanagedType.LPWStr)]
            internal string RemoteName;
            [MarshalAs(UnmanagedType.LPWStr)]
            internal string Comment;
            [MarshalAs(UnmanagedType.LPWStr)]
            internal string Provider;
        }

        [StructLayout(LayoutKind.Sequential)]
        internal struct NMHDR
        {
            internal IntPtr hwndFrom;
            internal IntPtr idFrom;
            internal int code;
        }

        [StructLayout(LayoutKind.Sequential)]
        internal struct NMHEADER
        {
            internal NativeMethods.NMHDR nmhdr;
            internal int iItem;
            internal int iButton;
            internal IntPtr pItem;
        }

        [StructLayout(LayoutKind.Sequential)]
        internal struct NMITEMACTIVATE
        {
            public NativeMethods.NMHDR hdr;
            public int iItem;
            public int iSubItem;
            public uint uNewState;
            public uint uOldState;
            public uint uChanged;
            public NativeMethods.POINT ptAction;
            public IntPtr lParam;
            public uint uKeyFlags;
        }

        [StructLayout(LayoutKind.Sequential)]
        public class NMLVKEYDOWN
        {
            public NativeMethods.NMHDR hdr;
            public short wVKey;
            public uint flags;
        }

        internal delegate IntPtr OfnHook(IntPtr hdlg, int msg, IntPtr wparam, IntPtr lparam);

        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
        internal struct OPENFILENAME
        {
            internal uint lStructSize;
            internal IntPtr hwndOwner;
            internal IntPtr hInstance;
            internal string lpstrFilter;
            internal IntPtr lpstrCustomFilter;
            internal uint nMaxCustFilter;
            internal uint nFilterIndex;
            internal SafeUnmanagedMemoryHandle lpstrFile;
            internal uint nMaxFile;
            internal IntPtr lpstrFileTitle;
            internal uint nMaxFileTitle;
            internal string lpstrInitialDir;
            internal string lpstrTitle;
            internal uint Flags;
            internal ushort nFileOffset;
            internal ushort nFileExtension;
            internal IntPtr lpstrDefExt;
            internal IntPtr lCustData;
            internal NativeMethods.OfnHook lpfnHook;
            internal string lpTemplateName;
            internal IntPtr pvReserved;
            internal uint dwReserved;
            internal uint FlagsEx;
        }

        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode), BestFitMapping(false, ThrowOnUnmappableChar = true)]
        internal sealed class OSVersionInfoEx
        {
            internal const uint VER_NT_WORKSTATION = 1;
            internal const uint VER_NT_DOMAIN_CONTROLLER = 2;
            internal const uint VER_NT_SERVER = 3;
            internal const uint VER_SUITE_ENTERPRISE = 2;
            internal const uint VER_SUITE_DATACENTER = 0x80;
            internal const uint VER_SUITE_PERSONAL = 0x200;
            internal const uint VER_SUITE_BLADE = 0x400;
            private static NativeMethods.OSVersionInfoEx s_versionInfo;
            internal int osVersionInfoSize;
            internal int majorVersion;
            internal int minorVersion;
            internal int buildNumber;
            internal int platformId;
            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 0x80)]
            internal string csdVersion;
            internal short servicePackMajor;
            internal short servicePackMinor;
            internal short suiteMask;
            internal byte productType;
            internal byte reserved;
            internal static NativeMethods.OSVersionInfoEx GetOsVersionInfo()
            {
                if (s_versionInfo == null)
                {
                    NativeMethods.OSVersionInfoEx ver = new NativeMethods.OSVersionInfoEx();
                    if (!NativeMethods.GetVersionEx(ver))
                    {
                        throw new Win32Exception(Marshal.GetLastWin32Error());
                    }
                    s_versionInfo = ver;
                }
                return s_versionInfo;
            }

            internal OSVersionInfoEx()
            {
                this.osVersionInfoSize = Marshal.SizeOf(this);
            }
        }

        [StructLayout(LayoutKind.Sequential)]
        internal struct POINT
        {
            internal int x;
            internal int y;
            internal POINT(int x, int y)
            {
                this.x = x;
                this.y = y;
            }
        }

        [StructLayout(LayoutKind.Sequential)]
        private struct POINTSTRUCT
        {
            internal int x;
            internal int y;
            internal POINTSTRUCT(int x, int y)
            {
                this.x = x;
                this.y = y;
            }
        }

        public enum ProcessorArchitecture
        {
            PROCESSOR_ARCHITECTURE_AMD64 = 9,
            PROCESSOR_ARCHITECTURE_IA64 = 6,
            PROCESSOR_ARCHITECTURE_INTEL = 0
        }

        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
        public struct QUERY_SERVICE_CONFIG
        {
            public int serviceType;
            public int startType;
            public int errorControl;
            public string binaryPathName;
            public string loadOrderGroup;
            public int tagId;
            public string dependencies;
            public string serviceStartName;
            public string displayName;
        }

        [StructLayout(LayoutKind.Sequential)]
        internal struct RECT
        {
            internal int left;
            internal int top;
            internal int right;
            internal int bottom;
            internal RECT(int left, int top, int right, int bottom)
            {
                this.left = left;
                this.top = top;
                this.right = right;
                this.bottom = bottom;
            }
        }

        internal enum ResourceDisplayType
        {
            RESOURCEDISPLAYTYPE_GENERIC,
            RESOURCEDISPLAYTYPE_DOMAIN,
            RESOURCEDISPLAYTYPE_SERVER,
            RESOURCEDISPLAYTYPE_SHARE,
            RESOURCEDISPLAYTYPE_FILE,
            RESOURCEDISPLAYTYPE_GROUP,
            RESOURCEDISPLAYTYPE_NETWORK,
            RESOURCEDISPLAYTYPE_ROOT,
            RESOURCEDISPLAYTYPE_SHAREADMIN,
            RESOURCEDISPLAYTYPE_DIRECTORY,
            RESOURCEDISPLAYTYPE_TREE,
            RESOURCEDISPLAYTYPE_NDSCONTAINER
        }

        internal enum ResourceScope
        {
            RESOURCE_CONNECTED = 1,
            RESOURCE_CONTEXT = 5,
            RESOURCE_GLOBALNET = 2,
            RESOURCE_RECENT = 4,
            RESOURCE_REMEMBERED = 3
        }

        [Flags]
        internal enum ResourceType : uint
        {
            RESOURCETYPE_ANY = 0,
            RESOURCETYPE_DISK = 1,
            RESOURCETYPE_PRINT = 2,
            RESOURCETYPE_RESERVED = 0xffffffff
        }

        [Flags]
        internal enum ResourceUsageType
        {
            RESOURCEUSAGE_ALL = 0x13,
            RESOURCEUSAGE_ATTACHED = 0x10,
            RESOURCEUSAGE_CONNECTABLE = 1,
            RESOURCEUSAGE_CONTAINER = 2,
            RESOURCEUSAGE_NOLOCALDEVICE = 4,
            RESOURCEUSAGE_SIBLING = 8
        }

        [StructLayout(LayoutKind.Sequential)]
        public struct SC_ACTION
        {
            public NativeMethods.SC_ACTION_TYPE Type;
            public uint Delay;
        }

        public enum SC_ACTION_TYPE : uint
        {
            SC_ACTION_NONE = 0,
            SC_ACTION_REBOOT = 2,
            SC_ACTION_RESTART = 1,
            SC_ACTION_RUN_COMMAND = 3
        }

        [StructLayout(LayoutKind.Sequential)]
        internal struct SECURITY_ATTRIBUTES
        {
            internal int nLength;
            internal IntPtr lpSecurityDescriptor;
            internal bool bInheritHandle;
        }

        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
        public struct SERVICE_FAILURE_ACTIONS
        {
            public uint dwResetPeriod;
            public string lpRebootMsg;
            public string lpCommand;
            public uint cActions;
            public IntPtr lpsaActions;
        }

        [StructLayout(LayoutKind.Sequential)]
        public struct SERVICE_FAILURE_ACTIONS_FLAG
        {
            public bool FailureActionsOnNonCrashFailures;
        }

        [Flags]
        public enum ServiceAccessRights : uint
        {
            SERVICE_ALL_ACCESS = 0xf01ff,
            SERVICE_CHANGE_CONFIG = 2,
            SERVICE_ENUMERATE_DEPENDENTS = 8,
            SERVICE_INTERROGATE = 0x80,
            SERVICE_PAUSE_CONTINUE = 0x40,
            SERVICE_QUERY_CONFIG = 1,
            SERVICE_QUERY_STATUS = 4,
            SERVICE_START = 0x10,
            SERVICE_STOP = 0x20,
            SERVICE_USER_DEFINED_CONTROL = 0x100
        }

        public enum ServiceConfig2InfoLevel : uint
        {
            SERVICE_CONFIG_DESCRIPTION = 1,
            SERVICE_CONFIG_FAILURE_ACTIONS = 2,
            SERVICE_CONFIG_FAILURE_ACTIONS_FLAG = 4
        }

        [Flags]
        public enum ServiceControlAccessRights : uint
        {
            SC_MANAGER_ALL_ACCESS = 0xf003f,
            SC_MANAGER_CONNECT = 1,
            SC_MANAGER_CREATE_SERVICE = 2,
            SC_MANAGER_ENUMERATE_SERVICE = 4,
            SC_MANAGER_LOCK = 8,
            SC_MANAGER_MODIFY_BOOT_CONFIG = 0x20,
            SC_MANAGER_QUERY_LOCK_STATUS = 0x10
        }

        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
        internal struct ShFileInfoW
        {
            internal IntPtr hIcon;
            internal int iIcon;
            internal int dwAttributes;
            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
            internal string szDisplayName;
            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)]
            internal string szTypeName;
        }

        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
        private struct SHFILEOPSTRUCT
        {
            internal IntPtr hwnd;
            internal uint wFunc;
            [MarshalAs(UnmanagedType.LPWStr)]
            internal string pFrom;
            [MarshalAs(UnmanagedType.LPWStr)]
            internal string pTo;
            internal ushort fFlags;
            internal bool fAnyOperationsAborted;
            internal IntPtr hNameMappings;
            [MarshalAs(UnmanagedType.LPWStr)]
            internal string lpszProgressTitle;
        }

        [StructLayout(LayoutKind.Sequential)]
        internal struct SID_AND_ATTRIBUTES
        {
            internal IntPtr Sid;
            internal uint Attributes;
        }

        [StructLayout(LayoutKind.Sequential)]
        public struct SYSTEM_INFO
        {
            public ushort wProcessorArchitecture;
            public ushort wReserved;
            public uint dwPageSize;
            public IntPtr lpMinimumApplicationAddress;
            public IntPtr lpMaximumApplicationAddress;
            public UIntPtr dwActiveProcessorMask;
            public uint dwNumberOfProcessors;
            public uint dwProcessorType;
            public uint dwAllocationGranularity;
            public ushort wProcessorLevel;
            public ushort wProcessorRevision;
        }

        [StructLayout(LayoutKind.Sequential)]
        internal struct TOKEN_GROUPS
        {
            internal uint GroupCount;
            internal NativeMethods.SID_AND_ATTRIBUTES Groups;
        }

        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
        internal class TOOLTIPTEXT
        {
            public NativeMethods.NMHDR hdr;
            public string lpszText;
            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)]
            public string szText;
            public IntPtr hinst;
            public uint uFlags;
        }

        [StructLayout(LayoutKind.Sequential, Pack = 1)]
        internal struct TV_HITTESTINFO
        {
            internal Point pt;
            internal uint flags;
            internal IntPtr hItem;
        }

        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto, Pack = 8)]
        internal struct TVITEM
        {
            internal uint mask;
            internal IntPtr hItem;
            internal uint state;
            internal uint stateMask;
            internal IntPtr pszText;
            internal int cchTextMax;
            internal int iImage;
            internal int iSelectedImage;
            internal int cChildren;
            internal IntPtr lParam;
        }

        internal class Util
        {
            // Methods
            internal static int HIWORD(int n)
            {
                return ((n >> 0x10) & 0xffff);
            }

            internal static int HIWORD(IntPtr n)
            {
                return HIWORD((int)((long)n));
            }

            internal static int LOWORD(int n)
            {
                return (n & 0xffff);
            }

            internal static int LOWORD(IntPtr n)
            {
                return LOWORD((int)((long)n));
            }

            internal static int MAKELONG(int low, int high)
            {
                return ((high << 0x10) | (low & 0xffff));
            }

            internal static IntPtr MAKELPARAM(int low, int high)
            {
                return (IntPtr)((high << 0x10) | (low & 0xffff));
            }

            internal static int SignedHIWORD(int n)
            {
                return (short)((n >> 0x10) & 0xffff);
            }

            internal static int SignedHIWORD(IntPtr n)
            {
                return SignedHIWORD((int)((long)n));
            }

            internal static int SignedLOWORD(int n)
            {
                return (short)(n & 0xffff);
            }

            internal static int SignedLOWORD(IntPtr n)
            {
                return SignedLOWORD((int)((long)n));
            }
        }

        [StructLayout(LayoutKind.Sequential)]
        internal struct WINDOWPOS
        {
            internal IntPtr hwnd;
            internal IntPtr hwndInsertAfter;
            internal int x;
            internal int y;
            internal int cx;
            internal int cy;
            internal int flags;
        }

        internal static class WindowsEditions
        {
            // Fields
            public const int PRODUCT_BUSINESS = 6;
            public const int PRODUCT_BUSINESS_N = 0x10;
            public const int PRODUCT_ENTERPRISE = 4;
            public const int PRODUCT_ENTERPRISE_N = 0x1b;
            public const int PRODUCT_HOME_BASIC = 2;
            public const int PRODUCT_HOME_BASIC_N = 5;
            public const int PRODUCT_HOME_PREMIUM = 3;
            public const int PRODUCT_HOME_PREMIUM_N = 0x1a;
            public const int PRODUCT_STARTER = 11;
            public const int PRODUCT_ULTIMATE = 1;
            public const int PRODUCT_ULTIMATE_N = 0x1c;
            public const int PRODUCT_UNDEFINED = 0;
        }

        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
        internal class WNDCLASS
        {
            internal int style;
            internal NativeMethods.WndProc lpfnWndProc;
            internal int cbClsExtra;
            internal int cbWndExtra;
            internal IntPtr hInstance = IntPtr.Zero;
            internal IntPtr hIcon = IntPtr.Zero;
            internal IntPtr hCursor = IntPtr.Zero;
            internal IntPtr hbrBackground = IntPtr.Zero;
            [MarshalAs(UnmanagedType.LPWStr)]
            internal string lpszMenuName;
            [MarshalAs(UnmanagedType.LPWStr)]
            internal string lpszClassName;
        }

        internal delegate IntPtr WndProc(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam);
    }
}
